gpt4 book ai didi

PowerShell 字符串插值语法

转载 作者:行者123 更新时间:2023-12-02 22:35:52 32 4
gpt4 key购买 nike

我总是使用以下语法来确保变量在字符串中展开:
"my string with a $($variable)"
我最近遇到了以下语法:
"my string with a ${variable}"
它们是等价的吗?有什么区别吗?

最佳答案

补充marsze's helpful answer :
${...} (将变量名括在 {} 中)确实是 如果变量名包含特殊字符,则总是必要的 ,例如 空格,. , 或 - .

  • 不特别的是_和 - surprisingly and problematically - ? .
  • 注::namespace variable notation 的上下文中,总是被解释为终止 PowerShell 驱动器引用。 ,无论是否{...}使用或需要使用机箱(例如,在 $env:USERNAME${env:USERNAME} 中,env 指的是表示所有环境变量的 PowerShell drive)。

  • 在字符串扩展的上下文中 (内插) "..." ,还有另一个原因要 使用 ${...} ,即使变量名本身不需要它:
    如果您需要 从紧跟在非空白字符之后的变量名 ,特别是包括 : :
    $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
    this answer有关 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.

    关于PowerShell 字符串插值语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60323111/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com