2
votes

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

1
Have you tried using the -AsString switch on Get-PowerBIAccessToken? This should write the value of the access token to the $env:headers variable rather than the type. You can then construct the hashtable in Task 2Nick Graham
@NickGraham sorry new to PowerShell, could you please provide an example on how to use the -AsString. ?Jayendran
$head = Get-PowerBIAccessToken -AsStringNick Graham
You might find it easier to get the access token and call Invoke-RestMethod in the same taskNick Graham
You’ll need to take a look at the structure of the hash table that is returned by Get-PowerBIAccessToken (without the -AsString switch). Then create a new hashtable with the same property(s). Create empty hashtable $headers = @{}. Then add the property $headers[“PropertyName”] = $env:headersNick Graham

1 Answers

1
votes

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'