1

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

2 Answers 2

2

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
1
  • 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)} } Mar 24, 2011 at 15:40
1

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.

3
  • How does this work if both of the arrays I'm going through are objects that have properties and aren't just strings? Mar 25, 2011 at 20:15
  • @Scott: Why are you using a CSV if you only have one property? Mar 27, 2011 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. Mar 28, 2011 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .