Here’s a short PowerShell function to retrieve a list of a user’s groups from Active Directory:
function getADGroups($username)
{
$root = ([adsi]"").distinguishedName;
$searcher = new-object System.DirectoryServices.DirectorySearcher($root);
$searcher.filter = "(&(objectClass=user)(sAMAccountName=$username))";
$user = $searcher.findall();
$groupNames = @();
if ($user.count -eq 1)
{
$groups = $user[0].Properties.memberof;
[regex]$regex = "^CN=(.*?),";
$groups | % {
$groupNames += $regex.matches($_) | % { $_.groups[1].value }
};
}
else
{
write-host "invalid username, result count:" $user.count -foregroundcolor "red";
}
$groupNames;
}
getADGroups "macke" | % { $_ }
geht auch ohne regex…
$user[0].Properties.memberof | % { ([adsi]”LDAP://$_”).samaccountname }