PowerShell eDirectory Group Membership Query

I found my self needing to query eDirectory for all the group objects and their members.  Below is the PowerShell script to accomplish this.  At its core, it is an LDAP query.

$ldapAssembly = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols");

function ldapQuery() {
    param($hostName,$authUser,$basedn,$filter);
    $eDirConnect = New-Object System.DirectoryServices.Protocols.LDAPConnection "$hostName";
    $eDirConnect.AuthType = [System.DirectoryServices.Protocols.AuthType]::Basic;
    $password = Read-Host -Prompt "Password" -AsSecureString;
    $queryCreds = New-Object "System.Net.NetworkCredential" -ArgumentList $authUser,$password;
 
    $eDirConnect.Bind($queryCreds);
 
    $scope = [System.DirectoryServices.Protocols.SearchScope]::subtree;
    $attrs = $Null;
    $query = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $basedn,$filter,$scope,$attrs;
    $eDirData = $eDirConnect.SendRequest($query);
    $eDirEntries = $eDirData.Entries;
    $eDirEntries;
    $eDirConnect.Dispose();
}

$eDirGroupData = ldapQuery -hostName "YoureDirServer" -authUser "cn=user,o=edir" -basedn "" -filter "(objectClass=Group)";

foreach ( $entry in $eDirGroupData ) {
    $groupCN = $entry.Attributes.cn[0];
 
    if ( $entry.Attributes.AttributeNames -contains "groupmember" ) {
        $memberCount = $entry.Attributes.groupmember.count;
        $i=0;
        while ( $i -lt $memberCount ) {
            $groupMember = $entry.Attributes.groupmember[$i];
            write-output "$groupCN,$groupMember";
        }
     } else {
         write-output "$groupCN";
     }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s