none
Powershell - get-aduser and exclude specific sub OU's RRS feed

  • Question

  • I've been beating my head against this and can't seem to get things working.  At the simple level, I have a particular query with GET-ADUSER that seems to work fine...

    get-aduser -searchbase "OU=ParentOU,OU=All Users,DC=domain.DC=local" -filter *

    This command works great, the problem is that I would like to exclude specific sub OU's beneath "ParentOU"  I have tried just about every combination I can think of....  Here is my latest attempt that does NOT work.  Any suggestions?

    get-aduser -SearchBase "OU=ParentOU,OU=All Users,DC=domain,DC=local" -filter {DistinguishedName
    -notlike "*,OU=SubOU,OU=ParentOU,OU=All Users,DC=domain,DC=local"}

    Wednesday, July 8, 2015 8:12 PM

Answers

  • I'd go with something like...

    Get-ADUser -Filter * -SearchBase 'OU=Parent,DC=Domain,DC=Local' | 
        Where-Object { $_.DistinguishedName -notlike '*OU=TheOneYouCareAbout,*' }
    That is, use Where-Object to filter them out.

    Wednesday, July 8, 2015 8:18 PM

All replies

  • I'd go with something like...

    Get-ADUser -Filter * -SearchBase 'OU=Parent,DC=Domain,DC=Local' | 
        Where-Object { $_.DistinguishedName -notlike '*OU=TheOneYouCareAbout,*' }
    That is, use Where-Object to filter them out.

    Wednesday, July 8, 2015 8:18 PM
  • Success!  Wow, I should have posted sooner.  Thank you very much.

    Regards, Adam Tyler

    Wednesday, July 8, 2015 8:41 PM
  • Correct, the answer is that you cannot filter on the distinguishedName attribute. You have to retrieve all and then exclude what you don't want.

    -- Bill Stewart [Bill_Stewart]

    Wednesday, July 8, 2015 8:48 PM
    Moderator
  • Quick follow up here...  When I attempt to use an "-or" statement to string multiple excluded OU's together it seems to break..  Where did I go wrong here?

    | Where-Object { ($_.DistinguishedName -notlike '*OU=SubOU1,*') -or ($_.DistinguishedName -notlike '*OU=SubOU2,*') }

    Wednesday, July 8, 2015 8:50 PM
  • Boolean logic.

    I think you mean -and rather than -or .

    If you say -or , it means "any of the -notlike conditions can be $true".

    If you say -and , it means "all of the -notlike conditions must be $true".


    -- Bill Stewart [Bill_Stewart]

    Wednesday, July 8, 2015 9:16 PM
    Moderator
  • Easier and more reliable:

     Where-Object {$_.DistinguishedName -notmatch 'SubOU1|SubOU2'}

    You can add as many as you need separated by pipes - |.


    \_(ツ)_/

    • Proposed as answer by Fred9777 Wednesday, June 21, 2017 3:14 PM
    Wednesday, July 8, 2015 9:53 PM