Public/Get-ADGroupMembers.ps1
<#
.SYNOPSIS Lists all members of a specified Active Directory group. .DESCRIPTION This function retrieves all members of a specified Active Directory group and returns their userPrincipalNames or sAMAccountNames based on the specified output format. .PARAMETER GroupName Specifies the name of the Active Directory group to list members. .PARAMETER OutputFormat Specifies the desired output format. Possible values are "upn" for userPrincipalNames and "samaccountname" for sAMAccountNames. Default is "upn". .EXAMPLE Get-ADGroupMembers -GroupName "Group1" Retrieves all members of the "Group1" Active Directory group in userPrincipalName format. .EXAMPLE Get-ADGroupMembers -GroupName "Group1" -OutputFormat "samaccountname" Retrieves all members of the "Group1" Active Directory group in sAMAccountName format. .NOTES Requires Active Directory module for PowerShell and appropriate permissions to query AD objects. #> Function Get-ADGroupMembers { [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string]$GroupName, [ValidateSet("samaccountname", "upn")] [string]$OutputFormat = "upn" ) $members = @() try { $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $Root = [ADSI]"LDAP://RootDSE" $Domain = $Root.Get("rootDomainNamingContext") $objSearcher.SearchRoot = New-Object ADSI("GC://$Domain") $objSearcher.PageSize = 1000 $strFilter = "(&(objectClass=group)(CN=$GroupName))" $objSearcher.Filter = $strFilter $objSearcher.SearchScope = "Subtree" $adgroup = $objSearcher.FindAll() if ($adgroup.count -gt 0) { $group = $adgroup[0].GetDirectoryEntry() foreach ($memberDN in $group.Properties["member"]) { $member = [ADSI]"LDAP://$memberDN" switch ($OutputFormat) { "upn" { $members += $member.Properties["userPrincipalName"].Value } "samaccountname" { $members += $member.Properties["sAMAccountName"].Value } } } $members } else { return $false } } catch { return $false } } |