我有以下代码,并且一直在尝试添加IF
语句,以便在找不到该项时,写入文本NotFound。
$csv1 = Import-Csv D:\MaintenanceWindow2.csv
$csv2 = Import-Csv D:\ScomAlerts.csv
$csv1 | Where {$field = $_.Computername;($csv2 | where {$_.Computername -eq $field})}
-Edit,这是我目前所拥有的,但似乎并没有选择每个服务器。
Import-Csv D:\2.csv | ForEach-Object {
$table[$_.Computername] = $_.'Collection Name'}
$Global:result = $AlertDataNoDupe | ForEach-Object { [PSCustomObject] @{
Server=$_.NetbiosComputerName
MaintenanceWindow=IF($table[$_.NetbiosComputerName]){$table[$_.NetbiosComputerName]}
ELSE{"Not found!"}
}
-Edit,添加样本数据
MaintenanceWindow2.csv:
"Computername","Collection Name"
"Server1","NA - All DA Servers - Patching - Cert - Thu 2:00"
"Server2","NA - All DA Servers - Patching - Cert - Thu 2:00"
ScomAlerts.csv:
ComputerName
Server2
Server3
答案 0 :(得分:2)
更新后的问题中的脚本应该可以正常工作。我要做的唯一更改是使用<book/occurrences/promotionNum>
并使用缩进,但这主要是为了提高可读性。
$table.ContainsKey("")
或
$MaintenanceWindows = @"
"Computername","Collection Name"
"Server1","NA - All DA Servers - Patching - Cert - Thu 2:00"
"Server2","NA - All DA Servers - Patching - Cert - Thu 2:00"
"@ | ConvertFrom-Csv
$ScomAlerts = @"
ComputerName
Server2
Server3
"@ | ConvertFrom-Csv
#Create hashtable
$table = @{}
#Add MWs to hashtable
$MaintenanceWindows | ForEach-Object { $table.Add(($_.ComputerName.Split(".")[0].Trim()), $_.'Collection Name')}
$Global:result = $ScomAlerts | ForEach-Object {
$computer = $_.ComputerName.Split(".")[0].Trim()
[PSCustomObject] @{
Server = $computer
MaintenanceWindow = if($table.ContainsKey($computer)){
$table[$computer]
} else{ "Not found!" }
}
}
$result
Server MaintenanceWindow
------ -----------------
Server2 NA - All DA Servers - Patching - Cert - Thu 2:00
Server3 Not found!