Azure DevOps Azure PowerShell任务输出变量

时间:2019-07-11 01:24:10

标签: azure-devops azure-powershell

enter image description here enter image description here enter image description here

我正在使用一个Azure PowerShell任务和PowerShell任务创建发布管道。在Azure Powershell任务中,我有以下代码

$groupInfos = @()
for ([int]$i = 0; $i -lt $azureADGroupsObj.Count)
{
    $groupInfo = New-Object PSObject
    $groupInfo | Add-Member -MemberType NoteProperty -Name "displayName" -Value $azureADGroupsObj[$i].DisplayName
    $groupInfo | Add-Member -MemberType NoteProperty -Name "Id" -Value 
    $azureADGroupsObj[$i].Id
    $groupInfos += $groupInfo
    $i++
}
return $groupInfos
Write-Host "##vso[task.setvariable variable=azureADGroups;]$groupInfos"

我试图在此处将$ groupInfos存储到azureADGroups变量中。

enter image description here

但是当我在同一任务下的下一步中运行PowerShell任务时,它说无法识别术语“ azureADGroup”。似乎没有设置变量。有人知道我在这里缺少什么吗? / p>

1 个答案:

答案 0 :(得分:2)

我在您的脚本中发现了3个问题:

  1. 您不需要设置参考名称。

  2. 在写变量命令之前有一个返回。因此,将不会执行写入变量命令。

  3. write variable命令只能使用单行字符串。但是,$ groupInfos是一个对象。它不会隐式转换为字符串。您需要使用“ ConvertTo-Json -Compress”命令将其转换为字符串。

我在管道中进行了测试:

$groupInfosString = $groupInfos | ConvertTo-Json -Compress
write-host $groupInfos
write-host $groupInfosString 
Write-Host "##vso[task.setvariable variable=azureADGroups;]$groupInfos"
Write-Host "##vso[task.setvariable variable=azureADGroupsFromString;]$groupInfosString "

从调试日志中,我们可以检查是否成功设置了变量“ azureADGroupsFromString”。

enter image description here

更新

您可以在下一个PS任务中使用以下脚本:

$objs = '$(azureADGroupsFromString)' | ConvertFrom-Json
foreach( $obj in $objs){
    Write-Host ("displayName:{0} Id:{1}" -f $obj.displayName, $obj.Id)
} 

输出:

enter image description here

更新:

如果要通过参数将其传递给下一个PS任务,请将该变量用单引号引起来。这样,它将被视为字符串。