1

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,*")}
tcox8
  • 13
  • 1
  • 1
  • 3

1 Answers1

3

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,*")}
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
  • Can you explain why I would use -and? Unless I'm thinking about this wrong, logically I am saying if the OU name is not "test" OR "TIS" then return the results. Seems that using -and operator is not what I want (unless I am thinking wrong) – tcox8 Jul 05 '16 at 18:46
  • @tcox8 With `-and` it has to satisfy both conditions in order to be true. If you use `-or` then one condition being true satisfies the operator and the other condition need not be tested. That is a problem since the computers cannot be in more than one OU. You want to be sure the computer is in neither OU so both have to be evaluated separately. – Matt Jul 05 '16 at 19:20
  • @tcox8 You're not saying "the OU name is not 'test' OR 'TIS'. You're saying "the OU name is not 'test and the OU name is not 'TIS'". See, you moved the "not". If you want to use `-or`, you'd have to say `where { -not (($_.DistinguishedName -like "*OU=Test,*") -or ($_.DistinguishedName -like "*OU=TIS,*")) }` which is logically the same. See [DeMorgan's Laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws). – Bacon Bits Jul 05 '16 at 19:27
  • Thank you for the clarification! – tcox8 Jul 05 '16 at 19:57