在变量名中使用变量字符串值

时间:2018-02-07 12:36:17

标签: powershell

应该像:

$part = 'able'

$variable = 5

Write-Host $vari$($part)

这应该打印" 5",因为那是$ variable的值。

我想使用它来调用几个具有相似但不相同名称的变量的方法,而不使用switch语句。如果我可以使用类似的东西来调用变量就足够了:

New-Variable -Name "something"

但是要调用变量,不要设置它。

编辑以添加我正在做的具体示例:

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

我希望看起来像这样:

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

1 个答案:

答案 0 :(得分:1)

您正在寻找Get-Variable -ValueOnly

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

您不必每次都需要解析ListBox引用时调用Get-Variable,而是可以根据部分名称预先推测哈希表,并使用它来代替:

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