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:

  1. function getADGroups($username)
  2. {
  3.   $root = ([adsi]"").distinguishedName;
  4.   $searcher = new-object System.DirectoryServices.DirectorySearcher($root);
  5.   $searcher.filter = "(&(objectClass=user)(sAMAccountName=$username))";
  6.   $user = $searcher.findall();
  7.  
  8.   $groupNames = @();
  9.   if ($user.count -eq 1)
  10.   {
  11.     $groups = $user[0].Properties.memberof;
  12.     [regex]$regex = "^CN=(.*?),";
  13.     $groups | % {
  14.       $groupNames += $regex.matches($_) | % { $_.groups[1].value }
  15.       };
  16.   }
  17.   else
  18.   {
  19.       write-host "invalid username, result count:" $user.count -foregroundcolor "red";
  20.   }
  21.   $groupNames;
  22. }
  23.  
  24. 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