Skip to content

Instantly share code, notes, and snippets.

@dnewsholme
Created December 16, 2022 11:44
Show Gist options
  • Save dnewsholme/049bc3a632117b27e9abcac53f078da4 to your computer and use it in GitHub Desktop.
Save dnewsholme/049bc3a632117b27e9abcac53f078da4 to your computer and use it in GitHub Desktop.
Get-UsersGroups
Function Get-UsersGroups{
param (
$username,
[switch]$recurse
)
#Initialize output variable
$groups = @()
#Search AD user and retrieve the groups removing the unwanted characters from the strings.
((((get-aduser $username -properties memberof).memberof) | `
% {$_ -split(",",2)} | `
select-string -Pattern "CN\=.+" -AllMatches).Matches).Value | `
? {$_ -notlike "*,*"} | `
% {$_ -replace ("CN=","")} | % {
$groups += New-object psobject -Property @{
"GroupName" = "$_"
}
}
#if the recurse switch is applied find the groups they are a member of from group nesting.
if ($recurse){
Foreach ($item in $groups.GroupName) {
$subgroups = try {(get-adgroup $item -properties memberof -ErrorAction stop).memberof}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
}
if ($subgroups -ne $null) {(($subgroups | ? {($_ -notlike "")} | `
% {$_ -split(",",2)} | `
select-string -Pattern "CN\=.+" -AllMatches).Matches).Value | `
? {$_ -notlike "*,*"} | `
% {$_ -replace ("CN=","")} | % {
$groups += New-object psobject -Property @{
"GroupName" = "$_"
}
}
}
}
}
#Output the groups array
return $groups
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment