PowerShell: Read user’s groups from Active Directory

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" | % { $_ }

Über uns Stefan

Polyglot Clean Code Developer

Ein Kommentar

  1. geht auch ohne regex…

    $user[0].Properties.memberof | % { ([adsi]“LDAP://$_“).samaccountname }

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax