问题描述
我在 Azure Devops Server 2020 的管道作业中有一个 Powershell 任务。这是 powershell 的一部分:
$xml = [xml](Get-Content $configPath)
Write-Output "Iterating over appSettings"
ForEach($add in $xml.configuration.appSettings.add)
{
#Write-Output "Processing AppSetting key $($add.key)"
$SecretvarKey = "MAPPED_"+$add.key
Write-Output $SecretvarKey
$matchingEnvVar = [Environment]::GetEnvironmentvariable($SecretvarKey)
if($matchingEnvVar)
{
Write-Output "Found matching environment variable for key: $($add.key)"
Write-Output "Replacing value $($add.value) with $matchingEnvVar"
$add.value = $matchingEnvVar
}
}
这在任务中运行良好——我的构建正在做我想要的。但是当我查看 YAML 时,我会看到这样的评论:
#Your build pipeline references an undefined variable named ‘$add.key’. Create or edit the build pipeline for this YAML file,define the variable on the Variables tab. See https://go.microsoft.com/fwlink/?linkid=865972
同样,这不会干扰脚本的执行。
然而,现在我想把这个任务提取到一个任务组中。当我这样做时,无害的误检测现在是一个问题,因为它坚持这些是新参数:
有什么我可以改变我的 Powershell 脚本的魔法,这样它们就不会被认为是参数吗?
解决方法
您的构建管道引用了一个名为“$add.key”的未定义变量
这是由以下行触发的:
Write-Output "Found matching environment variable for key: $($add.key)"
$($add.key)
被 Azure DevOps 解析为 macro syntax。您可以通过使用字符串格式来避免这种情况:
'Found matching environment variable for key: {0}' -f $add.key
顺便说一句,在大多数情况下,您不需要使用 Write-Output - 它既缓慢又多余。有关详细信息,请参阅此博文:Let’s Kill Write-Output。