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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With