PowerShell:- Single Quotes Versus Double Quotes – Day 01

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

  1. Double Quotes – Un-escaped
    • Our variable ( $myName ) is replaced with its contents ( Joanne )
  2. Double Quotes – Escaped  – `$myName ( `$ )
    • Our variable ( $myName ) is escaped using the backtick character ( ` )
    • Our variable ( $myName ) is kept as is $myName
  3. Single Quotes – Un-escaped
    • Our variable ( $myName ) is kept as is $myName

 

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s