2011-05-11 111 views

回答

23

雙引號允許變量擴展,而單引號不要:

PS C:\Users\Administrator> $mycolor="red" 
PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor' 
My favorite color is $mycolor 

來源:http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences

(我知道1.0版本,但原則仍然是相同的)

+0

太棒了。感謝那! – 2011-05-11 16:54:18

+0

onteria_引用的變量擴展也稱爲「[插值]」(http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/)「。你也可以把插值看作「連接的一個專用實例」,正如[Wikipedia](http://en.wikipedia.org/wiki/Variable_(computer_science)#Interpolation)提出的那樣。 – Stisfa 2011-10-06 01:14:13

+0

另請參見:[字符串和字符串中的可變擴展](http://blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx )由Jeffrey Snover撰寫,其中詳細介紹瞭如何在字符串中使用變量。 – 2011-11-20 14:21:59

2

這是不是想成爲更好的答案。只是另一種說法。

撇號和引號之間的變量擴展與UNIX shell(sh,ksh,bash)上的相同。使用撇號將按原樣使用字符串,而不處理任何轉義。

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 
相關問題