Use a variable to refer to the contents of the hash table

I am trying to access a hash table by name, which is passed through a parameter.

Ref.

TestScript.Ps1 -specify TestDomain1,TestDomain2 

Contents of TestScript.ps1:

 param( [string[]]$specify ) $TestDomain1 = @{"Name" = "Test1", "Hour" = 1} $TestDomain2 = @{"Name" = "Test2", "Hour" = 2} foreach($a in $specify) { write-host $($a).Name #This is where I would expect it to return the Name value contained in the respective # hash table. However when I do this, nothing is being returned } 

Is there any other way to do this to get these values? Is there a better method than using hash tables? Any help would be appreciated.

+4
source share
2 answers

Is there any other way to do this to get these values?

Yes, you could use the Get-Variable cmdlet.

 param( [string[]]$Specify ) $TestDomain1 = @{"Name" = "Test1"; "Hour" = 1} $TestDomain2 = @{"Name" = "Test2"; "Hour" = 2} foreach($a in $specify) { $hashtable = Get-Variable $a write-host $hashtable.Value.Name #This is where I would expect it to return the Name value contained in the respective # hash table. However when I do this, nothing is being returned } 

Is there a better way instead of using hash tables?

Using hash tables is not so much a problem as accessing a variable by name defined by the input. What if something passing the define parameter uses a string that refers to a variable that you don't want to refer to? @BartekB's solution is a good suggestion for a better way to achieve your goal.

+3
source

I would probably go with a hash hash:

 param ( [string[]]$Specify ) $Options = @{ TestDomain1 = @{ Name = 'Test1' Hour = 1 } TestDomain2 = @{ Name = 'Test2' Hour = 2 } } foreach ($a in $Specify) { $Options.$a.Name } 
+6
source

Source: https://habr.com/ru/post/1499012/


All Articles