Powershell: where {_.Name not in $object}

filtering, powershell

Solution

You were basically correct in using this in your title: "where {_.Name not in $object}"

Syntax is a little different. Pipe it to the following

Where { !($_.Name -in $excluded) }

OR

Where { $_.Name -notin $excluded }

Both seem to give the same results in the console. Happy coding!

Note: Tested this on PSv2 and v3.

I ran across this when looking for an answer and figured I would update with these options for others that run into this.

Problem

I'm building a script that lists all Inactive computer accounts. I'd like to exclude a few systems from the results. I've got a text-file containing all systems to be excluded (one systemname per line). All items are stored in an object with property name "name". So $excluded will contain: ``` name ---- system1 system2 ``` To list all inactive systems I use the Search-ADAccount cmdlet: ``` $InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true} ``` Of course I can loop all results 1 by 1, but is there a simple way to exclude the systems directly from the results? I've got a feeling it's possible with select-object or where-object, but I can't figure out how to compare against the results in an object.

Original source