CSV中的查找值和第二列的返回值

时间:2015-12-13 22:04:48

标签: csv powershell

我从SCOM中提取服务器列表,并希望根据包含以下数据的CSV检查此列表:

Computername,Collection Name
Server01,NA - All DA Servers - Patching - Cert - Thu 2:00
Server02,NA - All DA Servers - Patching - Prod - Wed 18:00

如果找到服务器,则返回集合名称。我只是不确定什么是最好的方法。

Import-Module OperationsManager

New-SCOMManagementGroupConnection -ComputerName SCOMsvr

$PendReboot = Get-ScomAlert -Criteria "Severity = 1 AND ResolutionState < 254 AND Name = 'Pending Reboot'" |
              Select NetbiosComputerName

$data = Import-Csv .\servers2.csv

$table = $data | Group-Object -AsHashTable -AsString -Property Computername

修改 - 第二次尝试代码:

$csv = Import-Csv D:\SCOM-Pend-Reboot.csv

$biglist = Import-Csv D:\servers2.csv

foreach ($line in $csv){
  $server = $line.NetbiosComputerName

  if ($server -eq $biglist.Computername) {
    "$server is in $biglist.'Collection Name'"
  } else {
    "$server is not found!"
  }
}

3 个答案:

答案 0 :(得分:1)

如果您将CSV数据分组,则必须访问此类信息,因为组项的值也包含Servername属性:

$server = 'Server01'
$table[$server].'Collection Name'

只有当您的CSV包含多个列时才有意义。但即便如此,我可能更喜欢自定义对象的hastable,以便服务器名称仅作为键出现:

$table = @{}
Import-Csv .\servers2.csv | ForEach-Object {
  $table[$_.Computername] = New-Object -Type PSCustomObject -Property @{
    'Collection Name' = $_.'Collection Name'
    'other property'  = ...
    ...
  }
}

如果CSV只有两列,那么创建哈希表会更简单:

$table = @{}
Import-Csv .\servers2.csv | ForEach-Object {
  $table[$_.Computername] = $_.'Collection Name'
}

这样你就可以直接查找名字了:

$server = 'Server01'
$table[$server]

答案 1 :(得分:0)

你可以这样做:

Import-Module OperationsManager

New-SCOMManagementGroupConnection -ComputerName SCOMsvr

$PendReboot = get-scomalert -Criteria "Severity = 1 AND ResolutionState < 254 AND Name = 'Pending Reboot'" | Select NetbiosComputerName

$data = Import-Csv .\servers2.csv

$table = $data | Group-Object -AsHashTable -AsString -Property Computername

foreach($server in $PendReboot) {
    if($table.ContainsKey($server)) {
        ($table.$server)."Collection Name"
    }
}

答案 2 :(得分:0)

过度复杂化的案例。

Thanks to this post我的回答很简单:

IF(-not(Get-SCOMAlert)){Import-Module OperationsManager}

New-SCOMManagementGroupConnection -ComputerName SCOM-Server

Get-SCOMAlert -Criteria "Severity = 1 AND ResolutionState < 254 AND Name = 'Pending'" | Select NetbiosComputerName | Export-Csv -NoTypeInformation -Path D:\SCOM-Pend-Reboot.csv

$csv = Get-Content 'D:\SCOM-Pend-Reboot.csv'
Import-Csv D:\servers2.csv | Where {$_ -match $csv.computername} | Sort Computername