字符串比较在powershell中不起作用
我正在使用字符串比较在 powershell 中尝试 if else 条件。我按照文档使用 -eq 运算符进行了尝试。但低于错误。这里“Build.Reason”是一个预定义的变量。不知道为什么要为变量寻找 cmdlet 名称。
Write-Host "$(Build.Reason)"
if ($(Build.Reason) -eq "Manual" ) {
$temp = "https://url/api/qualitygates/project_status?&pullRequest=$(Build.Reason)"
Write-Host "Manual"
} else {
Write-Host "CI"
}
错误
"C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:a_tempd7af16d6-ce3e-4dec-a636-9447962fdac4.ps1'"
Manual
Manual : The term 'Manual' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At D:a_tempd7af16d6-ce3e-4dec-a636-9447962fdac4.ps1:7 char:5
+ if (Manual -eq "Manual" ) {
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (Manual:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
回答
看起来像是CI 系统提供$(Build.Reason)的宏样式值(它不是PowerShell 构造),扩展为在PowerShell 看到它之前代码文字部分。
因此,如果在生成的 PowerShell 代码中将此值视为字符串,则需要引用它;例如:
if ("$(Build.Reason)" -eq "Manual") { # ...
请注意,如果有机会$(Build.Reason)扩展为带有嵌入 "字符的值,则必须将它们转义为`". 同样,如果值包含嵌入的$字符。,单-quoting应当使用,其可以然后需要转义嵌入式单引号为''。
如果无法在源执行此转义,您可以使用逐字此处的字符串:
if (@'
$(Build.Reason)
'@ -eq 'Manual') { # ...
重要提示:结束'@必须始终在行的开头。