【问题标题】:How to pass a variable having a dollar sign to another variable in PowerShell?如何将具有美元符号的变量传递给PowerShell中的另一个变量?
【发布时间】:2019-01-26 02:42:35
【问题描述】:

我正在使用本地服务器来运行 VSTS 构建/发布。 目前,我正在尝试将一个变量从 VSTS:$(password) 传递给我的脚本。 假设这个变量$(password)的值为'stringwith$sign'`

这个变量$(password)需要注入到我脚本中的一个字符串中:

$string = "I need to inject my password string from VSTS here "$(password)""

字符串应如下所示:

$string = I need to inject my password string from VSTS here "stringwith$sign"

我如何实现这一目标?如果我简单地将其添加为 $(password),构建/发布将失败,因为它认为 "stringwith$sign" 中的 $sign 是一个变量。我什至不能使用'' 引号,因为我的变量$(password) 需要插入$string

【问题讨论】:

  • 您能否提供一个小脚本来说明您遇到的问题?我很难理解你在问什么。
  • 一个精巧的例子:考虑一个 VSTS 变量 $(password)。假设 $password 是 'foo$pass' VSTS 中的自定义 powershell 任务具有以下字符串:$getUserPassword = "the password is $(password)"。在运行构建/发布时,当 VSTS 将 $(password) 插入 $getUserPassword 字符串时,这将失败,因为 PowerShell 会认为 'foo$pass' 中的 $pass 也是一个变量。希望这是有道理的。提前致谢。

标签: powershell azure-devops


【解决方案1】:

没有看到任何示例代码,很难判断您的脚本是如何工作的。

但基本上,如果您要设置包含特殊字符的字符串文字,则可以通过使用单引号而不是双引号来阻止它们被解析。例如,如果你执行

$password = "stringwith$sign"
$password

那么密码的值为stringwith

这是因为 powershell 已解析字符串并将 $sign 视为变量的名称,并尝试插入 $sign 的值。但是由于没有声明$sign,所以使用空字符串的默认值。

但是,如果您使用单引号,即

$password = 'stringwith$sign'
$password

那么密码的值为stringwith$sign

接下来,设置

$string = "I need to inject my password string from VSTS here ""$password""" 

赋予$string

的值

I need to inject my password string from VSTS here "stringwith$sign"

【讨论】:

    【解决方案2】:

    你也可以使用格式操作符:

    $myVar = 'okay$dollar'
    'My string with my var {0} inside' -f $myVar
    

    Get-Variable:

    $myVar = 'okay$dollar'
    "My string with my var $(Get-Variable myvar | select -expandproperty value) inside"
    

    【讨论】:

      【解决方案3】:

      您只需要使用 ${env:password} 格式而不是 $(password) 来获取变量密码的值。

      例如,如果您使用以下脚本添加 PowerShell 任务:

      $string="I need to inject my password string from VSTS here ${env:test}" 
      echo $string
      

      然后它将在构建日志中显示I need to inject my password string from VSTS here stringwith$sign

      【讨论】:

        猜你喜欢
        • 2021-06-29
        • 2021-09-28
        • 1970-01-01
        • 2012-04-17
        • 2021-08-10
        • 1970-01-01
        • 2011-04-27
        • 2019-05-02
        • 1970-01-01
        相关资源
        最近更新 更多