PowerShell 中单引号 (') 和双引号 (") 的区别是什么?
powershellmicrosoft technologiessoftware & coding更新于 2026/1/5 18:07:17
PowerShell 中的单引号 (‘) 和双引号 (“) 没有区别。这与 Python 等编程语言类似。我们通常同时使用两个引号来打印语句。
示例
PS C:\> Write-Output 'This will be printed using Single quote' This will be printed using Single quote PS C:\> Write-Output "This will be printed using double quote" This will be printed using double quote
但是当我们评估任何表达式或打印变量时,它会产生明显的差异。
$date = Get-Date Write-Output 'Today date is : $date' Today date is : $date Write-Output "Today date is : $date" Today date is : 11/02/2020 08:13:06
从上面的例子中可以看出,单引号无法打印变量输出,而是打印变量的名称,而双引号可以打印变量的输出。即使我们尝试计算变量名的值,也无法使用单引号来完成。
示例
PS C:\> Write-Output 'Today date is : $($date)' Today date is : $($date)
另一个乘法运算的例子,
PS C:\> Write-Output "Square of 4 : $(4*4)" Square of 4 : 16 PS C:\> Write-Output 'square of 4 : $(4*4)' square of 4 : $(4*4)
以使用数组打印多条语句为例。
示例
$name = 'Charlie' $age = 40 $str = @" New Joinee name is $name Her age is $age "@ $str
输出
New Joinee name is Charlie Her age is 40 He will receive 1200 dollar bonus after 2 years
上面的输出打印正确,但是当我们使用单引号时,它不会打印变量名。
示例
$str = @' New Joinee name is $name Her age is $age He will receive $($age*30) dollar bonus after 2 years '@
输出
New Joinee name is $name Her age is $age He will receive $($age*30) dollar bonus after 2 years
结论是,仅在打印纯文本时使用单引号,但在打印变量和评估字符串中的其他表达式时,在 PowerShell 中使用双引号。

