问题描述
我的azure piplines yaml脚本使用powershell用当前日期字符串替换.CS文件中的占位符字符串。这是要替换的行(20200101000000
)
[assembly: MyCompany.Net.Attributes.BuildDateAttribute("20200101000000")]
这是执行此操作的强大步骤
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
部分使用双引号,这样我就可以转义引号字符,但这似乎也不起作用。我猜想这是用这种方式编写脚本的局限性。
还有其他方法可以实现我想要的吗?
解决方法
您可以使用Get-Date -UFormat
来添加类似于.NET中DateTime.ToString()
函数的任意字符
'[Attrib("20200101000000")]' -replace '"20200101000000"',(get-date -UFormat '"%Y%m%d%H%M%S"')
,
Powershell中的转义字符是反引号(`),而不是反斜杠(\)。尝试例如"`"20200101000000`""
。