Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 663
Walter81 Avatar asked May 22 '12 08:05

Walter81


2 Answers

Import the exclude file (as csv) and use the -notcontains operator:

$names = Import-csv exclude.txt | Foreach-Object {$_.Name} 

$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $names -notcontains $_.Name}
like image 104
Shay Levy Avatar answered Oct 26 '22 05:10

Shay Levy


I think you can use -notcontains (TechNet article) operator:

$InactiveComputers = Search-ADAccount -AccountInactive -TimeSpan 90 -ComputersOnly | Where {$_.Enabled -eq $true -and $excluded -notcontains $_.name }
like image 45
jumbo Avatar answered Oct 26 '22 05:10

jumbo