Background
This morning I ran into a PowerShell problem that was a little harder than I will like to admit.
It had to do with a string that contains special characters.
Script
Code
$myName="Joanne"; # using double-quotes ( as is ) $log = "Variable $myName contains the value {0}" -f $myName; Write-Host $log # using double-quotes ( escaped - $ sign escaped as in `$) $log = "Variable `$myName contains the value {0}" -f $myName; Write-Host $log # using single-quotes $log = 'Variable $myName contains the value {0}' -f $myName; Write-Host $log
Output
Variable Joanne contains the value Joanne Variable $myName contains the value Joanne Variable $myName contains the value Joanne
Explanation
Here is how our variable ( $myName ) is treated
- Double Quotes – Un-escaped
- Our variable ( $myName ) is replaced with its contents ( Joanne )
- Double Quotes – Escaped – `$myName ( `$ )
- Our variable ( $myName ) is escaped using the backtick character ( ` )
- Our variable ( $myName ) is kept as is $myName
- Single Quotes – Un-escaped
- Our variable ( $myName ) is kept as is $myName