Powershell – Excluding Values from a CSV file in PowerShell

powershell

I'm trying to determine how to exclude values from an array based on a CSV file. This is the best option I have so far:

$arrIgnore = import-csv "ignore.csv"

foreach($objIgnore in $arrIgnore){
    $objAll = $objAll | where {$_.Name -ne $objIgnore.Name}
}

This doesn't filter out a single item from the array. If I write out the problem with the values in strings:

$objAll = $objAll | where {$_.Name -ne "value1"}
$objAll = $objAll | where {$_.Name -ne "value2"}

It works correctly. I'm sure I'm making a stupid mistake but I can't figure it out. 🙂

Best Answer

Does $objIgnore.Name exist? Check the output of $objIgnore.Name and make sure it contains what you think it does. I think $objIgnore.Name might be empty. If not, you still might have to cast it to a string from a PSObject. What does this output?

foreach($objIgnore in $arrIgnore){
    $objIgnore.Name
}

I was able to get the following code to work as you desired.

$arrIgnore = import-csv ".\ignore.csv"
$objAll = import-csv ".\all.csv"

foreach($objIgnore in $arrIgnore){
     $objAll = $objAll | where {$_.Name -ne $objIgnore.Name}
}

where ignore.csv contains

Name  
srv1  
srv2  
srv3  
srv4  
srv5

and all.csv contains

Name 
srv1 
srv2 
srv3 
srv4 
srv6 
srv5 
srv7 
srv8 
srv9 
srv10

At completion, $objAll returns

Name 
---- 
srv6 
srv7 
srv8 
srv9 
srv10