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

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

最佳答案

如果您像这样对 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]

关于csv - CSV 中的查找值和第二列的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256949/

相关文章:

excel - 为什么我的 VBA 宏在打开和关闭数百个 CSV 文件后停止?

powershell - Powershell在以分配的执行模式执行代码之前要求确认

powershell - 如何使用 PowerShell 将模块导入 Azure 自动化帐户?

azure - PowerShell 5.1 内联函数和其他函数有什么区别?

powershell - 用于在 PowerShell 中压缩文件夹的一行?

Python/Shell 脚本 - 合并 CSV 文件的 2 行,其中地址列具有 'New Line' 字符

perl - 如何告诉 DBD::CSV 使用逗号作为小数点分隔符?

python - CSV Python 序列错误

Python:获取给定文件夹中特定文件类型的名称

azure - 使用 powershell 重命名 AD 用户时出错