AdilZ
AdilZ

Reputation: 1197

Exclude items in array in Where-Object

I was wondering if there is a simple/single-line way of excluding an array of things using Where-Object.

So rather than go:

 $filtereddata = $data |
     Where {$_.var -ne "1"} |
     Where {$_.var -ne "2"} |
     Where {$_.var -ne "3"} |
     Where {$_.var -ne "4"} |
     Where {$_.var -ne "5"} |
     Where {$_.var -ne "7"} |
     Where {$_.var -ne "10"} |
     Where {$_.var -ne "12"} 

I go

 $filterddata = $data | Where {??????}

Or something like that...

Notice that they are all the same .Var.

Is there a way of doing this more simply? Especially say if, in an automated scenario, the number of Var to be excluded is ever growing?

Upvotes: 7

Views: 17567

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23355

$filtereddata = $data | Where{ $_.var -notin 1..12 }

You could use -notin with the .. array notation if your numbers are actually integers and not strings.

Otherwise you could have single where with multiple conditions joined with -or rather than piping to lots of additional where-object commands.

Upvotes: 10

Related Questions