本文介绍了在CSV中查找值,并从第二列返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从SCOM中提取服务器列表,并想对照包含以下数据的CSV检查该列表:

I'm pulling a server list from SCOM and want to check this list against a CSV which contains the following data:

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

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

If the server is found, return the Collection Name. I'm just unsure what would be the best approach.

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!"
  }
}

推荐答案

如果像这样对CSV数据进行分组,则必须访问此类信息,因为分组项的值包含Servername属性,如下所示:好吧:

If you group the CSV data like that you'll have to access the information like this, because the value of the group item contains the Servername property as well:

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

仅当CSV包含多个列时,这才有意义.但是即使那样,我可能还是希望有一个可定制对象的hastable,以便服务器名称仅作为键出现:

That only makes sense if your CSV has more than one column. But even then I'd probably prefer a hastable of custom objects so that the server name appears only as the key:

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

如果CSV仅包含两列,则创建哈希表将更简单:

If the CSV has just the two columns it'd be simpler to create the hashtable like this:

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

以便您可以直接查找名称:

So that you can look up the name directly:

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

这篇关于在CSV中查找值,并从第二列返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:18