Viktor Axén
Viktor Axén

Reputation: 319

Using a variables string value in variable name

It should work like:

$part = 'able'

$variable = 5

Write-Host $vari$($part)

And this should print "5", since that's the value of $variable.

I want to use this to call a method on several variables that have similar, but not identical names without using a switch-statement. It would be enough if I can call the variable using something similar to:

New-Variable -Name "something"

but for calling the variable, not setting it.

Editing to add a concrete example of what I'm doing:

Switch($SearchType) {
    'User'{
        ForEach($Item in $OBJResults_ListBox.SelectedItems) {
           $OBJUsers_ListBox.Items.Add($Item)
        } 
    }
    'Computer' {
        ForEach($Item in $OBJResults_ListBox.SelectedItems) {
            $OBJComputers_ListBox.Items.Add($Item)
        } 
    }
    'Group' {
        ForEach($Item in $OBJResults_ListBox.SelectedItems) {
            $OBJGroups_ListBox.Items.Add($Item)
        } 
    }
}

I want this to look like:

ForEach($Item in $OBJResults_ListBox.SelectedItems) {
   $OBJ$($SearchType)s_ListBox.Items.Add($Item)
}

Upvotes: 3

Views: 7602

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

You're looking for Get-Variable -ValueOnly:

Write-Host $(Get-Variable "vari$part" -ValueOnly)

Instead of calling Get-Variable every single time you need to resolve a ListBox reference, you could pre-propulate a hashtable based on the partial names and use that instead:

# Do this once, just before launching the GUI:
$ListBoxTable = @{}
Get-Variable OBJ*_ListBox|%{
  $ListBoxTable[($_.Name -replace '^OBJ(.*)_ListBox$','$1')] = $_.Value
}

# Replace your switch with this
foreach($Item in $OBJResults_ListBox.SelectedItems) {
    $ListBoxTable[$SearchType].Items.Add($Item)
}

Upvotes: 2

Related Questions