Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable to refer to contents of hash table

I'm trying to refer to a hash table by name that is passed in via a parameter.

Ex.

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 another way to be doing this to get these values? Is there a better method rather than using the hash tables? Any help would be appreciated.

like image 465
tylerauerbeck Avatar asked Aug 26 '13 18:08

tylerauerbeck


2 Answers

I would probably go with hash of hashes:

param (
    [string[]]$Specify
)

$Options = @{
    TestDomain1 = @{
        Name = 'Test1'
        Hour = 1
    }
    TestDomain2 = @{
        Name = 'Test2'
        Hour = 2
    }
}
foreach ($a in $Specify) {
    $Options.$a.Name
}
like image 106
BartekB Avatar answered Nov 14 '22 14:11

BartekB


Is there another way to be doing 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 method rather than using the hash tables?

Using hash tables is not so much of a problem as referring to a variable by a name defined by input. What if something passing the specify parameter used a string that referred to a variable you did not want to access? @BartekB's solution is a good suggestion for a better method of achieving your goal.

like image 31
dugas Avatar answered Nov 14 '22 14:11

dugas