Get members from all groups starting/ending or contains with search phrase

In this article you will find script for getting members from groups based on keyword. If your environment contains thousands of groups it might be difficult to find quickly specific groups and get their direct members. To do this you can use function pasted below.

To find group members we can just use Get-ADGroup command:

(Get-ADGroup -Identity $item -Properties members).members

Apart from that script will check also members details like emailaddress and WhenChanged date:

$UserDetails = Get-Aduser -Identity $username -Properties EmailAddress,WhenChanged
  
$Object = New-Object PSObject -Property @{ 
    
      GroupName              = $Item
      UserName               = $Username
      EmailAddress           = $UserDetails.EmailAddress
      ModifyDate             = $UserDetails.WhenChanged
   
}

Usage:

Get-Groups -SearchCriteria StartsWith -Phrase PowerShell
Get-Groups -SearchCriteria EndsWith -Phrase PowerShell
Get-Groups -SearchCriteria Contains -Phrase PowerShell

Final script:

Function Get-Groups {
    [CmdletBinding()]        
  
    # Parameters used in this function
    Param
    (
        [Parameter(Position=0, Mandatory = $true, HelpMessage="Select searching criteria(StartsWith, Contains, EndsWith)", ValueFromPipeline = $true)][ValidateSet("StartsWith", "EndsWith", "Contains")][string]
        $SearchCriteria,
 
        [Parameter(Position=1, Mandatory = $true, HelpMessage="Please type searching phrase", ValueFromPipeline = $true)] 
        $Phrase
    ) 
 
    $ErrorActionPreference = "Stop"
    $GroupsArray = @()
    $Path = "C:\users\$env:username\desktop\$phrase.csv"
 
    # Checking AD module
    Try
    {
        Import-Module ActiveDirectory
    }
    Catch
    {
        $_.Exception.Message
        Break
    }
 
    If($SearchCriteria -eq "StartsWith")
    {
        $SearchPhrase = "$Phrase" + "*"
    }
    ElseIf($SearchCriteria -eq "EndsWith")
    {
        $SearchPhrase = "*" + "$Phrase"
    }
    Else
    {
        $SearchPhrase = "*" + "$Phrase" +"*"
    }
    
    Try
    {
        $Groups = (Get-ADGroup -Filter {name -like $SearchPhrase} -Properties  samaccountname).samaccountname                     
    }
    Catch
    {
        Return 'Error:' + $_.Exception.Message
        Break
    }
         
    If($Groups)
    {
        Write-Host "`nNumber of groups: "$Groups.count "`n"
     
        ForEach($Item in $Groups)
        {
            Write-Host "Checking group: $item" -ForegroundColor Green
 
            Try
            {
                $Members = (Get-ADGroup -Identity $item -Properties members).members | Get-ADObject -Properties name,objectclass | Select-Object name,objectclass
            }
            Catch
            {
                Return 'Error:' + $_.Exception.Message
                Continue
            }
         
            If($Members)
            {
                ForEach($Member in $Members)
                {
                    If($Member.objectclass -eq "user")
                    {
                        $Username = $Member.name
                        $Username
                        $UserDetails = Get-Aduser -Identity $username -Properties EmailAddress,WhenChanged
 
                        $Object = New-Object PSObject -Property @{ 
   
                            GroupName              = $Item
                            UserName               = $Username
                            EmailAddress           = $UserDetails.EmailAddress
                            ModifyDate             = $UserDetails.WhenChanged
  
                        }
                
                        # Add custom object to our array
                        $GroupsArray += $Object
                    }
                }
            }
        }
    }
 
    If($GroupsArray)
    {
        # Save results in CSV file on your desktop
        Try
        {
            $GroupsArray | Export-Csv -Force -notype "$Path"
        }
        Catch
        {
            return 'Error:' + $_.Exception.Message
            Break
        }
    }
 
}

Check previous article about getting group membership details – link.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.