I am trying to get latest test result id to attach my screenshot in azure devops. I have added a powershell script task,
Some variable use in the script is dynamic and azure ask me to put them in the task group parameters,
I just added 123 as default value, but this task fails because of this.
Script:
$AzureDevOpsPAT = "123"
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$UriOrga = "https://dev.azure.com/{org}/{proj}/"
$uriAccount = $UriOrga + "_apis/test/runs?api-version=6.0"
$response = Invoke-RestMethod -Uri $uriAccount -Headers $AzureDevOpsAuthenicationHeader -Method Get
$testRunsIdSorted = $response.value | sort-object id -Descending
$result = Invoke-RestMethod -Uri https://dev.azure.com/{org}/{proj}/_apis/test/runs/$($testRunsIdSorted[0].id)?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
Write-Host "results = $($result | ConvertTo-Json -Depth 100)"
Write-Host "##vso[task.setvariable variable=runId]$($result.id | ConvertTo-Json -Depth 100)"
The error in the task I get after execution;
How can I define the variable in powershell?
It looks like you're adding the Powershell $ variable accessor to the Task Group Parameters. You've also wrapped some of your script in $(), which will tell the pipeline that you're attempting to access a Task Group variable. That is incorrect. The $() pipeline syntax is used to access pipeline variables, but not local powershell variables.
For example, this is correct syntax:
Write-Host "$(AzureDevOpsPAT)"
You'll want to update your parameters to have named variables instead of Powershell variable names.
I've updated your script and corrected the variable use:
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$(AzureDevOpsPAT)")) }
$UriOrga = "https://dev.azure.com/{org}/{proj}/"
$uriAccount = $UriOrga + "_apis/test/runs?api-version=6.0"
$response = Invoke-RestMethod -Uri $uriAccount -Headers $AzureDevOpsAuthenicationHeader -Method Get
$testRunsIdSorted = $response.value | sort-object id -Descending
$result = Invoke-RestMethod -Uri https://dev.azure.com/{org}/{proj}/_apis/test/runs/$testRunsIdSorted[0].id?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
$results = $result | ConvertTo-Json -Depth 100
Write-Host "results = $results"
Write-Host "##vso[task.setvariable variable=runId]$result.id"
Note, that you'll need to go back into your task group properties and reset the default value for the PAT after replacing your current content with this. After that, you'll need to update your pipeline to set the AzureDevOpsPAT parameter when you consume this task.