Powershell : Check if AD User is Member of a Group

We can find if an Active Directory user is member of an AD group using Get-ADGroupMember cmdlet. In this article, I am going to write powershell script to check if user is exists in a group or nested group, and check multiple users are member of an AD group.

Run the following command to import Active Directory cmdlets.

Import-Module ActiveDirectory

Powershell scipt to check if User is Member of a Group

The following powershell script checks whether the given user is member of the given group. We are using the parameter -Recursive with Get-ADGroupMember cmdlet to get nested group members along with direct group members.

$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"
}

Check if multiple users are member of a Group

Use the below powershell command to check if multiple users are member of a Group.

$users = "TestUser1","TestUser2"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
ForEach ($user in $users) {
    If ($members -contains $user) {
      Write-Host "$user exists in the group"
 } Else {
      Write-Host "$user not exists in the group"
}}
Advertisement