Powershell 在变量名称中使用变量字符串值
它的工作原理应该是:Powershell 在变量名称中使用变量字符串值,powershell,Powershell,它的工作原理应该是: $part = 'able' $variable = 5 Write-Host $vari$($part) 这应该打印“5”,因为这是$variable的值 我想用它来调用几个具有相似但不完全相同名称的变量的方法,而不使用switch语句。如果我可以使用类似于以下内容的方法调用变量就足够了: New-Variable -Name "something" 而是调用变量,而不是设置它 编辑以添加我正在做的具体示例: Switch($SearchType) { '
$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)
}
您正在寻找:
不必每次需要解析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)
}
这看起来不错。我也可以用它来调用一个方法吗?”$(获取变量“vari$part”-ValueOnly).methodname()虽然我的GUI在使用此方法而不是switch语句时运行速度明显较慢,但它仍然有效。你知道为什么,以及它是否可以用除此和switch语句之外的另一种方式求解吗?@ViktorAxén不是每次都进行变量查找,你可以创建一个哈希表,并使用它进行查找
# 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)
}