获取另一个数组的匹配值

时间:2017-08-22 10:03:28

标签: arrays powershell variables combobox

我有一个导出的输出列表:

"Account Name","Caller Computer Name"
"Adminuser123","Server123"
"Guest","Server778"
"Mike","Server007"
  • 该列表可以在"Account Name"以及"Caller Computer Name"
  • 中随机包含多个相同的项目

还有一个充满用户的组合框(通过从其他地方列出来完成填充)。 每当从组合框中选择用户时→检查用户是否存在于输出列表中→如果是,则在文本框中写入服务器名称,否则写入未知。

我做了什么:(只是核心部分)

$combobox.add_SelectedIndexChanged($combobox_SelectedIndexChanged)
$combobox_SelectedIndexChanged = {
  If ($Row = $csv | Where-Object {$_.'Account Name' -eq $combobox.SelectedItem}) {
    $lockstatus.Text = "Locked on: $($Row.'Caller Computer Name')"
  } else {
    $lockstatus.Text = "Locked on: Unknown"
  }
}

问题是每次我想引用那个$($Row.'Caller Computer Name')我只得到第一个索引项而不是我应该根据$combobox.SelectedItem

如何在代码中稍后引用该值如果我想稍后使用该项目? 例如,如果我选择用户Mike,它将写入"Locked on: Server007",我想稍后在代码中引用该值(在我们的示例server007中)并将该项/变量插入到其他字符串中,如:

$button.add_Click( 
{
Write-Host ($Row.'Caller Computer Name')
}

点击按钮后,您可以看到“Server007

2 个答案:

答案 0 :(得分:0)

您可以将exported output list读入哈希数组:

$HashAccounts = @{}
ForEach ($Row in (Import-Csv 'ExportedOutputList.csv')) {
    $HashAccounts.Add($Row.'Account Name',$Row.'Caller Computer Name')
}

使用“帐户名称”作为密钥来检索关联值:

$combobox.add_SelectedIndexChanged($combobox_SelectedIndexChanged)
$combobox_SelectedIndexChanged = {
  If ($HashAccounts[$combobox.SelectedItem]) {
    $lockstatus.Text = "Locked on: $($HashAccounts[$combobox.SelectedItem])"
  } else {
    $lockstatus.Text = "Locked on: Unknown"
  }
}

答案 1 :(得分:0)

$combobox.add_SelectedIndexChanged($combobox_SelectedIndexChanged)
$combobox_SelectedIndexChanged = {
  $Row = $csv | Where-Object {$_.'Account Name' -eq $combobox.SelectedItem}  
  If ($Row) {
    $lockstatus.Text = "Locked on: $($Row.'Caller Computer Name')"
  } else {
    $lockstatus.Text = "Locked on: Unknown"
  }
}