2

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.

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82

1 Answers1

6

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 ...
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206