powershellactive-directoryou

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


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,*")}

Solution

  • 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,*")}