Search code examples
powershellazure-devopshashtable

How to write "System.Collections.Hashtable" variable in Azure DevOps PowerShell


I'm having a variable of type System.Collections.Hashtable I want to write this value in azure DevOps variable in Powershell script and need to use the variable in the below tasks.

Variable created in azure DevOps: header

Task 1

Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId $env:tenant_id
$head = $null
$head = @{}
$head = Get-PowerBIAccessToken
Write-Host ("##vso[task.setvariable variable=headers]$head")

Task 2

Write-Host "Header is " $env:headers

Invoke-RestMethod -Headers $env:headers -Uri 'https://api.powerbi.com/v1.0/myorg/groups'

But the issue in Task 2 is

Header is System.Collections.Hashtable
Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to type "System.Collections.IDictionary".

Since the value of the header is simply assigning the string of System.Collections.Hashtable and not the actual value


Solution

  • If you call Invoke-RestMethod in the same task you avoid the complexity of writing the token into an Azure DevOps variable.

    Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId $env:tenant_id
    $head = $null
    $head = @{}
    $head = Get-PowerBIAccessToken
    
    Invoke-RestMethod -Headers $head -Uri 'https://api.powerbi.com/v1.0/myorg/groups'