Powershell: Find all computers in AD but exclude certain OU's

tcox8 picture tcox8 · Jul 5, 2016 · Viewed 7.1k times · Source

I am trying to list all computers in my domain except for those stored in any of the two OU's. As soon as I add the second OU using the -or operator things break.

Using this I return all computers except for those stored in my first unwanted ou:

[array]$Computers1 = get-adcomputer -filter '*' -SearchBase 'ou=WorkStations,dc=XXX,dc=XXX,dc=edu' | where { $_.DistinguishedName -notlike "*OU=Test,*" }

Adding the -Or operator causes the unwanted computers (those stored in both of these OU's) to be included in my results.

[array]$Computers1 = get-adcomputer -filter '*' -SearchBase 'ou=WorkStations,dc=XXX,dc=XXX,dc=edu' | where { ($_.DistinguishedName -notlike "*OU=Test,*") -or ($_.DistinguishedName -notlike "*OU=TIS,*")}

Answer

Bacon Bits picture Bacon Bits · Jul 5, 2016

You want -and, not -or:

[array]$Computers1 = get-adcomputer -filter '*' -SearchBase 'ou=WorkStations,dc=XXX,dc=XXX,dc=edu' |
    where { ($_.DistinguishedName -notlike "*OU=Test,*") -and ($_.DistinguishedName -notlike "*OU=TIS,*")}