Thursday, 16 July 2015

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

Advertisements
Advertisements

3 comments:

  1. Hi,

    Can we apply this script on OU? I mean I check of users of specific OU are member of a Group so please tell me is to possible to do so? if yes then please tell me how.

    Thanks & Regards,
    Yasaar

    ReplyDelete
    Replies
    1. Yes, you can apply this script to OU. I have posted new article for your need. please check this: http://www.morgantechspace.com/2016/11/check-if-ad-users-from-ou-are-member-of-group-powershell.html


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

      Delete
  2. function test-groupMemberShip($user,$group,$dc)
    {
    $t = $null
    [boolean]$retValue = $false
    try
    {

    $t = Get-ADGroupMember -Identity $group -Server $dc
    if($t -ne $null)
    {
    if ( $t | select SamAccountName | Where-Object { $_.samaccountName -ccontains $user } )
    {
    $retValue = $true
    }
    else
    {
    $retValue =$false
    }

    }
    }
    catch
    {
    $retValue =$false
    }
    return $retValue
    }

    ReplyDelete