Compilenix's Blog - PowerShell: Get Ad-Group membership by user

RSS Feed | Find Stuff

Get all groups (SID's and sAMAccountName) of the current user using PowerShell and without the need for ActiveDirectory-Modules or some other foo.


$AdUser=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$DomainName=[System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().Name;
$DomainName=$DomainName[0..$($DomainName.IndexOf('.') - 1)] -join "";
$GroupSids=@();
$GroupAccountNames=@();

$AdUser.Groups | ForEach-Object {
    $GroupSid = $_.Value;
    $GroupAccountNames += (New-Object System.Security.Principal.SecurityIdentifier($_.Value)).Translate([System.Security.Principal.NTAccount]).ToString() | Where-Object { 
        $_.ToLower().StartsWith("$DomainName");
    } | ForEach-Object {
        $_.ToLower().TrimStart("${DomainName}\");
        $GroupSids += $GroupSid;
    };
};

If you want to query for an other than the current user, replace the first line with the following one:


Add-Type -AssemblyName System.DirectoryServices.AccountManagement;
$AdUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity([System.DirectoryServices.AccountManagement.ContextType]::Domain, "Compilenix");

Note: To find out which input format's are supported visit the MSDN documentation -> here.