Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using non-string as $env: variable

I'd like to store a hashtable in an environmental variable--is that possible in Powershell?

Here's how I'm testing this:

$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?

like image 405
Yevgeniy Avatar asked Nov 13 '22 19:11

Yevgeniy


1 Answers

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

$global:hashtableVariable = @{
   'key1' = 'value1'
   'key2' = 'value2'
}

PowerShellScriptFile-2.ps1

$global:hashTableVariable.GetEnumerator() | ForEach-Object {
       Write-Host "$($_.Key):$($_.Value)"
}
like image 165
CodeCowboyOrg Avatar answered Jan 01 '23 22:01

CodeCowboyOrg