Finding Organizational Units

Get-OrganizationalUnit (from Microsofts free RSAT tools) can search for organizational units based on fully distinguished name or GUID, or you can use the –Filter parameter.

Unfortunately, -Filter cannot easily be automated. The code below does not work and will not return all organizational units with “Test” in their name:

$Name = 'Test'
Get-ADOrganizationalUnit -Filter { Name -like "*$Name*" }

This is surprising since this line works (provided you have organizational units with “Test” in their name in the first place:

Get-ADOrganizationalUnit -Filter { Name -like "*Test*" }

Often, a simple LDAP filter works best and can help if you’d like to search with simple wildcards. The code below finds all organizational units with “Test” in their name:

$Name = 'Test'
Get-ADOrganizationalUnit -LDAPFilter "(Name=*$Name*)"

Twitter This Tip! ReTweet this Tip!

  • If you place your wildcards in the variable and remove the quotes from the command the first sample will run:

    $Name = '*Test*'

    Get-ADOrganizationalUnit -Filter { Name -like $Name }

  • Or just use a string instead of a script block for your filter:

    $Name = 'Test'

    Get-ADOrganizationalUnit -Filter "Name -like '*$Name*'"

  • Wilson1 hit on the problem with the code. The Filter parameter expects a string not a script block. When you pass a script block the ToString() function is called to convert to a string. So:

    { Name -like "*$Name*" }.ToString()

    Is:

    Name -like "*$Name*"