Can an array variable defined in Azure DevOps "variable group"

12,405

Solution 1

It is suggested to only pass variables as string. If you want to pass an object to other tasks, you can use "ConvertTo-Json -Compress" to convert it to a json string.

$objectString = $object | ConvertTo-Json -Compress
Write-Host "##vso[task.setvariable variable=objectString;]$objectString"

And in the next PS task, you can pass it as environment variable. But, please enclose the variables in single quotes.

enter image description here

And then you can use "ConvertFrom-Json" to convert the string to an object.

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

Solution 2

I just pass the variable in as a string and then split it to create an array in PowerShell

Variable = Prod1,Prod2,Prod3

$array = $variable.Split(',)

If need be you can add a Trim to the end in case there are spaces

Variable = Prod1,Prod2 ,Prod3

$array = $workspaces.Split(',').trim()
Share:
12,405
wenbo
Author by

wenbo

Updated on June 08, 2022

Comments

  • wenbo
    wenbo almost 2 years

    I want to define some variables in Azure devops "variable group" which will be used in Powershell, but when the variable type is string it works, but some is array or object went wrong. mine look like below. left is the name,right is the value

    vmAlertedArray_backup => @("wbubuntu","wbubuntu2")

    1.when in azure devops script I use, it went wrong

    $vmAlertedArray_backup = $env:vmAlertedArray_backup foreach($c in $vmAlertedArray_backup){ Write-Host "$c" }

    2.below in powershell in local works

    $vmAlertedArray_backup = @("wbubuntu","wbubuntu2") foreach($c in $vmAlertedArray_backup){ Write-Host "$c" }

    Can any one show some experience about this? thanks