【问题标题】:PowerShell string interpolation syntaxPowerShell 字符串插值语法
【发布时间】:2020-06-04 23:11:14
【问题描述】:

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

"my string with a $($variable)"

我最近遇到了以下语法:

"my string with a ${variable}"

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

【问题讨论】:

  • $() 是子表达式运算符。它可以包含复杂的表达式或简单的东西,比如访问成员属性。 ${} 语法适用于变量名称具有特殊符号的情况,否则标准 $variable 将无法正确计算。
  • $() 也可以在字符串之外使用,以将多个由“;”分隔的管道组合在一起。

标签: powershell syntax string-interpolation


【解决方案1】:

补充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.

【讨论】:

    【解决方案2】:

    ${variable} 是包含特殊字符的变量名的语法。

    (见about_Variables -> Variable names that include special characters

    例子:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多