【问题标题】:Difficulty escaping quote character in powershell script (Azure Devops Yaml)在 powershell 脚本(Azure Devops Yaml)中难以转义引号字符
【发布时间】:2020-11-03 18:43:59
【问题描述】:

我的 azure piplines yaml 脚本使用 powershell 将 .CS 文件中的占位符字符串替换为当前日期字符串。这是要替换值的行 (20200101000000)

[assembly: MyCompany.Net.Attributes.BuildDateAttribute("20200101000000")]

这是执行此操作的 powershell 步骤

pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "20200101000000", (get-date -f 'yyyyMMddhhmmss')} | set-content -path $(versionFile)
  displayName: 'Update time stamp file'

我想更改此步骤以在搜索字符串周围包含引号字符",并将它们与新日期一起写入新输出值。但我似乎无法做到这一点。

我错误地尝试将转义的引号字符 \" 放在搜索和替换字符串中。但我猜你不能在单引号字符串中转义,所以它不起作用

pwsh: (get-content -path $(versionFile)) | foreach-object {$_ -replace "\"20200101000000\"", (get-date -f '\"yyyyMMddhhmmss\"')} | set-content -path $(versionFile)

这是错误:

##[command]"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1'"
ParserError: D:\a\_temp\80625e52-1302-4e35-a799-223ab893bcf1.ps1:3
Line |
   3 |  … lyInfo.cs) | foreach-object {$_ -replace "\"20200101000000\"", (get-d …
     |                                                ~~~~~~~~~~~~~~~~~
     | Unexpected token '20200101000000\""' in expression or statement.
##[error]PowerShell exited with code '1'.

我还尝试在脚本的 get-date 部分周围使用双引号,这样我就可以转义引号字符,但这似乎也不起作用。我猜这是以这种方式编写脚本的限制。

还有其他方法可以实现我想要的吗?

【问题讨论】:

    标签: powershell azure-yaml-pipelines


    【解决方案1】:

    您可以改用Get-Date -UFormat 添加任意字符,类似于.NET 中的DateTime.ToString() 函数

    '[Attrib("20200101000000")]' -replace '"20200101000000"', (get-date -UFormat '"%Y%m%d%H%M%S"')
    

    【讨论】:

      【解决方案2】:

      Powershell 中的转义字符是反引号 (`),而不是反斜杠 (\)。尝试例如"`"20200101000000`"".

      【讨论】:

        猜你喜欢
        • 2021-01-20
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        • 2017-01-27
        相关资源
        最近更新 更多