Check if AD Users from OU are Member of a Group using Powershell

We can use the Active Directory powershell cmdlet Get-ADGroupMember to check if an AD user is member of an AD group. In this article, I am going to write powershell script to find if users of specific OU are member of a Group.

Run the following command to import Active Directory cmdlets.

Import-Module ActiveDirectory

Find AD Users from OU are Member of a Group

We can use the cmdlet Get-ADUser to get AD users from specific OU and enumerate the users to check their membership in the particular group. We can use the parameter -Recursive with Get-ADGroupMember cmdlet to get nested group members along with direct group members. The following powershell command select users from the Organization Unit ‘TestOU’ and check the users are member of ‘Domain Admins’ group.

$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
$users | ForEach-Object {
$user = $_.Name
If ($members -contains $user) {
      Write-Host "$user exists in the group"
} Else {
      Write-Host "$user not exists in the group"
}}

Check if Single User is Member of a Group

The following powershell command find if particular single user is member of ‘Domain Admins’ group.

$user = "TestUser"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name

If ($members -contains $user) {
      Write-Host "$user exists in the group"
 } Else {
        Write-Host "$user not exists in the group"
}
Advertisement

1 thought on “Check if AD Users from OU are Member of a Group using Powershell”

Leave a Comment