Friday, February 28, 2014

The difference between single and double quotes in PowerShell

I had a colleague ask me the other day about whether there was a difference between using single or double quotes when defining a string variable in PowerShell. For that specific questions, the answer was "no". However, there is an important distinction to make between the two.

With double quotes, the text within the quotes will be parsed. For instance, the following code will output "Hello Marcus":

$name = 'Marcus'
$output = "Hello $name"
write-host $output

However, when changing the second line to using single quotes as so:

$output = 'Hello $name'

The output will instead be "Hello $name"

The parsers handling of the different quotes also means that if you are to use escape characters, for instance `n, you have to put the string within double quotes for the escape characters to work. If you want to use a double quote within such a string, you can write it using the escape character:

$mystring = "This is a variable called `"mystring`""

Having the possibility of using the two different quotes can also allow for creating strings that contain one of the two quote characters, for instance when building query strings:

$name = 'Marcus'
$query = "SELECT Id, City from Customers WHERE Name LIKE '%$name%'"

Knowing this difference between single and double quotes is quite crucial for being able to build PowerShell scripts and not get into a mess when trying to create dynamic execution of other scripts or programs that require parameters to be passed to them.