PowerShell Function: Get-ADAuthGroups

Here’s a PowerShell Function that leverages Active Directory .Net to get a list of the AD authorization groups. This is extremely useful to get a complete list of security groups that comprise a user’s AD Kerberos token without having to loop or recurse AD groups.

 

Function GetAuthGroups
{
Param
(
$AccountID,
[switch]$CountAuthGroups,
[Switch]$ReturnGroups = $True
)

$ErrorActionPreference = "SilentlyContinue"
[int]$UserAuthGroupsCount = 0

$UserAuthGroups = $NULL
$UserAuthGroupsDN = $NULL

$Assembly = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
$Context = New-Object -typename "System.DirectoryServices.AccountManagement.PrincipalContext" -ArgumentList $([System.DirectoryServices.AccountManagement.ContextType]::Domain)

$UserAccount = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($Context,$([System.DirectoryServices.AccountManagement.IdentityType]::SAMAccountName),$AccountID)

[array]$UserAuthGroups = $UserAccount.GetAuthorizationGroups()

$UserAccount.GetAuthorizationGroups() | ForEach { [array]$UserAuthGroupsDN += $_.DistinguishedName }
[int]$UserAuthGroupsCount = $UserAuthGroups.Count

IF ($UserAuthGroups.Count -eq 0)
{ [int] $UserAuthGroupsCount = $UserAuthGroupsDN.Count }

IF ($CountAuthGroups -eq $True)
{ return $UserAuthGroupsCount }

IF ($ReturnGroups -eq $True)
{
IF ($UserAuthGroups)
{ return $UserAuthGroups }
IF ($UserAuthGroupsDN)
{ return $UserAuthGroupsDN }
}

}

(Visited 450 times, 1 visits today)