Created
December 16, 2022 11:44
-
-
Save dnewsholme/049bc3a632117b27e9abcac53f078da4 to your computer and use it in GitHub Desktop.
Get-UsersGroups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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