3

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)
}
0

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

This looks right. Can I use this to call a method as well? '$(Get-Variable "vari$part" -ValueOnly).methodname()'
This worked, although my GUI runs noticeably slower when using this method rather than the switch-statement. Any Idea as to why and if it's solveable in another way than this and the switch-statement?
@ViktorAxén Instead of doing the variable lookup everytime, you could create a hashtable once and use that for the lookup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.