首页 > 解决方案 > PowerShell 字符串插值语法

问题描述

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

"my string with a $($variable)"

我最近遇到了以下语法:

"my string with a ${variable}"

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

标签: powershellsyntaxstring-interpolation

解决方案


为了补充marsze 的有用答案

${...}如果变量名包含特殊字符{,例如空格、、}.-

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

如果您需要直接从非空白字符后面描述变量名称,特别是包括:

$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 字符串扩展规则的全面概述,请参阅此答案

请注意,在将不带引号的参数传递给命令的上下文中,隐式应用字符串扩展时,您需要相同的技术;例如:

# 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

最后,一个有点晦涩的替代方法是`-escape 变量名后面的第一个字符,但问题是这仅适用于不属于转义序列的字符(请参阅参考资料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.

推荐阅读