我有以下代码,并一直在尝试添加一个IF
语句,以便在找不到该项目时编写文本NotFound。
$csv1 = Import-Csv D:MaintenanceWindow2.csv
$csv2 = Import-Csv D:ScomAlerts.csv
$csv1 | Where {$field = $_.Computername;($csv2 | where {$_.Computername -eq $field})}
-编辑,这是我目前拥有的,但它似乎并没有选择每个服务器。
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!"}
}
-编辑,添加示例数据
维护窗口2.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
更新后的问题中的脚本应该可以正常工作。我要做的唯一更改是使用$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!
或
Compare-Object -ReferenceObject $MaintenanceWindows -DifferenceObject $ScomAlerts -Property Computername -IncludeEqual -PassThru |
Where-Object { $_.SideIndicator -match '==|=>' } |
Select-Object ComputerName, @{n="Collection Name";e={ if($_."Collection Name"){ $_."Collection Name" } else { "Not Found!" } }}
Computername Collection Name
------------ ---------------
Server2 NA - All DA Servers - Patching - Cert - Thu 2:00
Server3 Not Found!