补充marsze's helpful answer:
如果变量名包含
special字符,例如
空格、. 或 -。
在"..." 内部的字符串扩展(插值)上下文中,另一个理由使用${...} ,即使变量名本身不需要它:
如果您需要从紧跟在非空白字符后面的字符中划定变量名,特别是包括::
$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。
请注意,在将不带引号的参数传递给命令的情况下,隐式应用字符串扩展时需要相同的技术;例如:
# 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.