PowerShell 字符串插值语法

PowerShell string interpolation syntax

我总是使用以下语法来确保变量在字符串中展开:

"my string with a $($variable)"

我最近运行进入以下语法:

"my string with a ${variable}"

它们等价吗?有什么区别吗?

${variable} 是包含 特殊字符 .

的变量名称的语法

(参见 about_Variables -> 包含特殊字符的变量名 )

示例:

${var with spaces} = "value"
"var with spaces: ${var with spaces}"

所以在你的情况下,它基本上与简单地写 $variable

相同

补充

${...}(将变量名括在{}中)确实是如果变量名称包含 特殊字符 ,例如 空格、.-,则总是 是必需的].

  • 特别的是_和-surprisingly and problematically-?.
  • 注意:在 [=32= 的上下文中,: 总是 被解释为终止 PowerShell 驱动器引用 ]代表所有环境变量)。

字符串扩展(插值)的上下文中"...",还有另一个 使用 ${...} 的原因,即使变量名称本身不需要它:

如果您需要从紧跟在非空白字符之后的变量名中区分出来,特别是包括::

$foo = 'bar'  # example variable

# INCORRECT: PowerShell assumes that the variable name is 'foobarian', not 'foo'
PS> "A $foobarian."
A .  # Variable $foobarian doesn't exist -> reference expanded to empty string.

# CORRECT: Use {...} to delineate the variable name:
PS> "A ${foo}barian."
A barbarian.

# INCORRECT: PowerShell assumes that 'foo:' is a *namespace* (drive) reference
#            (such as 'env:' in $env:PATH) and FAILS:
PS> "$foo: bar"
Variable reference is not valid. ':' was not followed by a valid variable name character. 
Consider using ${} to delimit the name.

# CORRECT: Use {...} to delineate the variable name:
PS> "${foo}: bar"
bar: bar

有关 PowerShell 字符串扩展规则的全面概述,请参阅 this answer

请注意,在传递未加引号的参数[=71]的情况下,隐式应用字符串扩展时,您需要相同的技术=]到一个命令;例如:

# INCORRECT: The argument is treated as if it were enclosed in "...",
#            so the same rules apply.
Write-Output $foo:/bar

# CORRECT
Write-Output ${foo}:/bar

最后,一个有点晦涩的替代方法是 `-转义变量名后的第一个字符,但问题是这仅适用于不属于 [=49= 的字符]转义序列(参见about_Special_Characters):

# OK: because `: is not an escape sequence.
PS> "$foo`: bar"
bar: bar

# NOT OK, because `b is the escape sequence for a backspace character.
PS> "$foo`bar"
baar # The `b "ate" the trailing 'r' of the variable value
     # and only "ar" was the literal part.