Home » PowerShell » Get AdUsers Exclude Specific OU in Active Directory

Get AdUsers Exclude Specific OU in Active Directory

To get adusers excluding specific OU in the active directory, you can use the Get-AdUser cmdlet with the SearchBase parameter to get all the users from the parent OU and use the where condition to get adusers excluding specific OU.

To exclude specific sub OU’s beneath Parent OU and get adusers from all other OU, we will have to use the Where-Object command to filter where the distinguishedname of the OU is not like the specific sub OU which we want to exclude.

In this article, we will discuss how to get adusers to exclude specific OU in the Active Directory using the Get-AdUser cmdlet.

Get AdUser Exclude Specific OU

Use the Get-AdUser cmdlet with the SearchBase parameter to specify the parent OU. It returns all the active directory users from the parent OU and sub OU.

Pipe the output of the first command where it returns all the adusers from OU to Where-Object to apply filter where it checks if distinguishedname is not like the OU which we want to exclude.

 Get-ADUser -Filter * -SearchBase 'OU=SHELLUSERS,DC=SHELLPRO,DC=LOCAL' | Where-Object { $_.DistinguishedName -notlike '*OU=HR*' } | Select Name,DistinguishedName

In the above PowerShell script, it gets adusers excluding the specific OU ( HR) and displays the aduser name and DistinguishedName.

It returns the adusers from Finance and SHELLUsers OU’s and excludes adusers from HR OU.

The output of the above PowerShell script to get aduser to exclude specific OU is:

Get AdUsers Exclude Specific OU
Get AdUsers Exclude Specific OU

Conclusion

I hope the above article on how to get adusers and exclude a specific OU using the Get-AdUser cmdlet is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.