Is it possible to use a variable to store input value(s) and then use the variable to invoke hash table value(s) using PowerShell?

Viewed 27

I'm not sure how to explain what I'm trying to do but maybe the code will help you understand. I might get a few terms wrong, I'm still learning.

I was not unable to find any documentation that would help my case. I feel like I'm complicating things and I could just use a lot of "if" statements but this seemed to be a way more efficient way (if it's possible) for what I'm trying to accomplish.

I am trying to invoke multiple Hash values with the "foreach" statement using the "read-host" inputs.

#Hash
$AppGroupsHash = @{
1 = "AppADGroup1" 
2 = "AppADGroup2" 
3 = "AppADGroup3" 
4 = "AppADGroup4" 
}

$AppGroups = $AppGroupsHash.Values -as [string[]]

#write-host for flair and choices to choose from.
Write-Host "`n1 = AppADGroup1`n2 = AppADGroup1`n3 = AppADGroup1`n4 = AppADGroup1`n  " -ForegroundColor Yellow

#User input value(s) for the required task
#Not sure if [string] is necessary in front of $AppGroupsKeys 
[string]$AppGroupsKeys = Read-Host "Enter App Hash values (1 - 2 - 3 - 4) (No space, delimit with ';') "

foreach ($AppGroupsKey in $AppGroupsKeys.split(';')) 
{
        if ($AppGroupsHash.Keys -ccontains $AppGroupsKey) 
        {
        #To test if it will print the values I'm trying to invoke
        echo $AppGroupsKey 

        #This is where I'm getting into trouble
        $AppGroupsHash.($AppGroupsKey) 
        } 
} 

When I run it. This is what I get, Read-Host Values: 1;3;4 :

#These are the values being echoed but the "$AppGroupsHash.($AppGroupsKey)" does not work
1
3
4 

What it should print out:

#Test "echo values"
1
3
4 

#The "values" I want
AppADGroup1
AppADGroup3
AppADGroup4

I want to use the variables I've inputted as the Keys that are stored in the hash so that I can invoke those values, these will be eventually used to add users to those groups based on their requirements.

This is what I tried:

foreach ($AppGroupsKey in $AppGroupsKeys.split(';')) 
{
        if ($AppGroupsHash.Keys -ccontains $AppGroupsKey) 
        {
        #To test if it will print the values I'm trying to invoke
        echo $AppGroupsKey 

        #This is where I'm getting into trouble
        write-host "$AppGroupsHash.$AppGroupsKey;"
        } 
} 

Output:

1
System.Collections.Hashtable.1;
2
System.Collections.Hashtable.2;
4
System.Collections.Hashtable.4;

I feel like it's possible but I also feel like I'm missing some sort of secret syntax for this to work.

Is it possible what I want to accomplish or should I try Arrays or just a bunch of "if" statements?

0 Answers
Related