Search code examples
powershellactive-directorypowershell-4.0get-aduser

how to get users whose OU includes the keyword: terminated


In Active Directory, I have "Ex Domain Users" folder including a bunch of folders. There are four folders having "Terminated" keyword that I need to retrieve the users from them.

In my powershell script, I do it like below:

$users  = Get-ADUser -Filter * -SearchBase “OU=Terminated,OU=Ex Domain Users,DC=xxx,DC=local”; 
$users += Get-ADUser -Filter * -SearchBase “OU=Terminated (ESA),OU=Ex Domain Users,DC=xxx,DC=local”;
$users += Get-ADUser -Filter * -SearchBase “OU=Terminated (Last week),OU=Ex Domain Users,DC=xxx,DC=local”; 
$users += Get-ADUser -Filter * -SearchBase “OU=Terminated (Last month),OU=Ex Domain Users,DC=xxx,DC=local”;

I am looking for a way to say ... -Searchbase "OU in ('%Terminated%'), ...") but I couldn't find the correct syntax or approach for it. Any help would be appreciated.

Regards.


Solution

  • Use Get-ADOrganizationalUnit to enumerate the relevant OUs before calling Get-ADUser against each:

    $targetOUs = Get-ADOrganizationalUnit -Filter 'Name -like "*Terminated*"'
    
    $users = $targetOUs |ForEach-Object {
      Get-ADUser -Filter * -SearchBase $_.distinguishedName
    }
    

    Beware that the Get-AD* cmdlets performs a subtree query by default, but you can restrict the scope to immediate children of the OU if necessary:

    Get-ADUser -SearchScope OneLevel ...