Simple questions that's been bugging me: In powershell, I can define strings like so:
$s1 = "Boogety boo"
or
$s2 = '.net rocks'
Is there a differe开发者_开发百科nce to the interpreter?
Double quotes allow variable expansion while single quotes do not:
PS C:\Users\Administrator> $mycolor="red"
PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor'
My favorite color is $mycolor
Source: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences
(I know version 1.0 but the principle is still the same)
This is not trying to be a better answer. Just another way to say it.
The variable expansion between apostrophes and quotes are the same as on UNIX shells (sh, ksh, bash). Using apostrophes will take the character string as-is, without processing any escapes.
PS C:\Users\lit> $x = "`t"
PS C:\Users\lit> $x
PS C:\Users\lit> Write-Output "now${x}is"
now is
PS C:\Users\lit> $x = '`t'
PS C:\Users\lit> $x
`t
PS C:\Users\lit> Write-Output "now${x}is"
now`tis
PS C:\Users\lit> $word = "easy"
PS C:\Users\lit> "PowerShell is $word"
PowerShell is easy
PS C:\Users\lit> 'PowerShell is $word'
PowerShell is $word
This question has a direct answer in the about_Quoting_Rules article of the PowerShell docs:
Double-quoted strings
A string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign (
$
) are replaced with the variable's value before the string is passed to the command for processing.For example:
$i = 5 "The value of $i is $i."
The output of this command is:
The value of 5 is 5.
Single-quoted strings
A string enclosed in single-quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed. For example:
$i = 5 'The value of $i is $i.'
The output of this command is:
The value of $i is $i.
In other words, use single quotes if you want your string to remain as written. Use double quotes, if you want to insert variables ($myVariable
), results of command executions and other evaluations ($($myList -join ', ')
) or special characters (`r
, `n
, `t
, `a
, etc.).
精彩评论