Home Β» PowerShell Β» PowerShell Variable in Single Quotes

PowerShell Variable in Single Quotes

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:

Hello $username

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

In the above PowerShell script, the variable $introMsg has a string embedded within the double quotes. It allows the expansion of a variable in strings.

The output of the above script is:

Hello, Shell Admin

Conclusion

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.

Leave a Comment