Working with strings is an essential part of the PowerShell script. Variables are used to store values such as strings or numbers, and quotes (single or double) in string plays a significant role in PowerShell and how it interprets strings and expands variables within them.
In this article, we will discuss how to use the PowerShell variable in single quotes, how to handle special characters, and expands variables in strings.
Using Single Quotes in PowerShell
Single quotes (‘ ‘) are used to define literal strings in PowerShell. Variables within single quotes are treated as plain text.
$userName = 'Shell Admin' $introMsg = 'Hello, $userName' Write-Host $introMsg
In the above PowerShell script, single quotes are used to define variables and contain plain text, and are not expanded. The output of the above PowerShell script is:
Handle Apostrophes and Special Characters
Use two consecutive apostrophes (”) to include apostrophes within a single quote string.
$strMsg = 'It''s a very beautiful day' Write-Host $strMsg
In the above PowerShell script, the
$strMsg variable stores the string in a single quote. It has apostrophes characters (It’s) within the string. To handle the special character, use two consecutive apostrophes.
The output of the above PowerShell script is:
PS D:\> $strMsg = 'It''s a very beautiful day' PS D:\> Write-Host $strMsg It's a very beautiful day PS D:\>
PowerShell Variable Expansion with Quotes
Double quotes ( ” “) in PowerShell allow variable expansion within strings.
$userName = 'Shell Admin' $introMsg = "Hello, $userName" Write-Host $introMsg
The output of the above script is:
Hello, Shell Admin
I hope the above article on PowerShell variables in single quotes and handling special characters is helpful to you.
Single quotes don’t allow variable expansion. It preserves the literal text. Double quotes allow variable expansion.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.