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. :-)

link|improve this question

71% accept rate
feedback

2 Answers

up vote 1 down vote accepted

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
link|improve this answer
I think I needed to cast it to a string because the following is what worked: foreach($objIgnore in $arrIgnore){ $objAll = $objAll | where {$_.Name -ne ($objIgnore.Name)} } – Scott Warren Mar 24 '11 at 15:40
feedback

FYI, an easier way to do this is to use the -notcontains operator with your array of strings that you want to ignore.

For example:

$array = @('value1','value2','value3','value4','value5')
$array | Where-Object {@('value2','value3') -notcontains $_}

This passes through your array containing all objects once instead of one time for each value you want to exclude.

link|improve this answer
How does this work if both of the arrays I'm going through are objects that have properties and aren't just strings? – Scott Warren Mar 25 '11 at 20:15
@Scott: Why are you using a CSV if you only have one property? – JasonMArcher Mar 27 '11 at 5:52
@JasonMArcher In this exact script the CSV actually has two properties, the name of a VM and the host it should reside on. I'm trying to filter out the VMs that have an assigned host. – Scott Warren Mar 28 '11 at 12:04
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.