user4317867
user4317867

Reputation: 2448

Add an IF into CSV filtering loop

I've got the following code and have been trying to add an IF statement so that if the item is not found, write the text NotFound.

$csv1 = Import-Csv D:\MaintenanceWindow2.csv
$csv2 = Import-Csv D:\ScomAlerts.csv    
$csv1 | Where {$field = $_.Computername;($csv2 | where {$_.Computername -eq $field})}

-Edit, here is what I currently have but it doesn't seem to pick every server.

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, adding sample data

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

Upvotes: 0

Views: 48

Answers (1)

Frode F.
Frode F.

Reputation: 54881

The script in your updated question should work fine. The only changes I would make is to use $table.ContainsKey("") and use indents, but that's mostly for readability.

$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!

or

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!

Upvotes: 2

Related Questions