Friday, August 13, 2010

PowerShell, double and single quotes

Powershell and quotes can be a bit confusing sometimes.

Double-quoted strings are subject to variable substitution, while single-quoted strings are not.

For example, let's launch a PowerShell console:

C:\Users\User>$x="hello"
C:\Users\User>"$x"
hello
C:\Users\User>'$x'
$x
C:\Users\User>
Let's write now a very small script that outputs a single parameter:

C:\Users\User>'param($p) "$p"' > .\test.ps1
C:\Users\User>type .\test.ps1
param($p) "$p"

Here's the output when calling that script with double- and single-quoted strings:

C:\Users\User>$x="hello"
C:\Users\User>.\test.ps1 "$x"
hello
C:\Users\User>.\test.ps1 '$x'
$x
C:\Users\User>.\test.ps1 -p "hello world"
hello world
C:\Users\User>.\test.ps1 -p 'hello world'
hello world
Which makes sense, because in PowerShell both single and double quotes serve to form strings with spaces.

Now, let's open a normal command prompt and try a few things:

C:\Users\User>powershell -file test.ps1 -p "hello"
hello
C:\Users\User>powershell -file test.ps1 -p 'hello'
'hello'
C:\Users\User>set XYZ="hello world"
C:\Users\User>powershell -file .\test.ps1 %XYZ%
hello world
C:\Users\User>set XYZ='hello world'
C:\Users\User>powershell -f .\test.ps1 %XYZ%
'hello
Which is expected too, because in a DOS command prompt, only double quotes will form strings with spaces, and single-quotes are taken as literals.

No comments: