Search code examples
powershellpowershell-3.0azure-powershell

Can not retrieve variable of type System.Collections.Hashtable in powershell console


I'm trying to retrieve a variable of type hastable from a PowerShell script execution.

explanation :

I execute te script using ./scriptName.ps1 -PAT ***** As you can see, I created an environment variable $env:Head in the script in order to get an output of the $header variable. The $header variable is of type hastable in the script, but when I display the $env:Head in the powershell console, it shows the string System.Collections.Hashtable

I would like to get the hashtable like :

Name                           Value
----                           -----
authorization                  Basic ********

Do you know how to get the hashtable content instead of the this string content?

Thank you for any help.

param (
    [string]$PAT
)

$Personal_Access_Token = "$PAT"
$user = ""
$token = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $Personal_Access_Token)))
$header = @{authorization = "Basic $token"}
$env:Head = $header.psobject.ImmediateBaseObject

enter image description here


Solution

  • I have reproduced in my environment and got expected results as below:

    Here is the changed script(updated your script):

    param (
        [string]$PAT
    )
    
    $Personal_Access_Token = "$PAT"
    $user = ""
    $token = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $Personal_Access_Token)))
    $header = @{authorization = "Basic $token"}
    $global:Head = $header.psobject.ImmediateBaseObject
    

    enter image description here

    Used $global here. This will ensure global scope which will allow you to get values in Console.