Question:
I’d like to store a hashtable in an environmental variable–is that possible in Powershell?
Here’s how I’m testing this:
1 2 3 4 |
$env:test = @{} $env:test $env:test|gm |
And getting confused, because output is:
System.Collections.Hashtable
TypeName: System.String
Name MemberType Definition
—- ———- ———- Clone Method System.Object Clone()
CompareTo Method int CompareTo(System.Object
value), int CompareTo(string strB)
…
… So when I return $env:test directly, I get ‘Hashtable’, but when I pipe it to get-member,
system.string is returned. Can someone please explain this behaviour?
Answer:
Environment variables ($env:stringVariable) are strings. However, it appears you want to make a non-string variable of type hashtable global. That can be done by using the global modifier ($global:hashtableVariable). This will allow you to access the variable from one script file in another as demostrated here
PowerShellScriptFile-1.ps1
1 2 3 4 5 |
$global:hashtableVariable = @{ 'key1' = 'value1' 'key2' = 'value2' } |
PowerShellScriptFile-2.ps1
1 2 3 4 |
$global:hashTableVariable.GetEnumerator() | ForEach-Object { Write-Host "$($_.Key):$($_.Value)" } |