【问题标题】:Is there a way to escape a variable call in powershell?有没有办法在powershell中转义变量调用?
【发布时间】:2020-03-10 12:14:42
【问题描述】:

我正在尝试使用 powershell 为 Visual Studio 生成 build.include 脚本。它们都使用${variable} 作为引用变量的一种方式。

我想知道是否有办法在字符串中转义。

例如

$string = @'
This is a `${string} I want to escape and {0} one I do not want to
'@ -f $Var

我在网上查了一下,上面说要转义 $ 你必须使用反引号。不过似乎不适用于变量?

【问题讨论】:

    标签: string powershell escaping


    【解决方案1】:

    也许使用以下语法:

    $Var = 'one'
    
    $string = @"
    This is a `$Var I want to escape and {0} I do not want to
    "@ -f $Var
    
    $string
    

    生成以下输出:

    This is a $Var I want to escape and one I do not want to
    

    另一种选择是嵌入变量:

    @"
    This is a `${Var} I want to escape and $Var I do not want to
    "@
    

    一些备注:

    • 这里的字符串总是在双引号@""@之间
    • 要转义字符,请使用反引号 `

    【讨论】:

    • 感谢您的回复!我实际上也需要花括号,尽管看起来。因为这就是视觉工作室将如何阅读它。正如我需要${variable} 实际显示在字符串内部而不是变量的值
    • 用括号更新答案。
    【解决方案2】:

    我想通了。你必须放双括号。

    例子:

    $string = @'
    This is a ${{string}} I want to escape and {0} one I do not want to
    '@ -f $Var
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2021-09-29
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多