Get Windows Group Members Using Powershell

I am a big fan of the Powershell scripting language for windows. I was recently asked how to verify what Windows and Active Directory accounts were assigned to groups across an entire domain. I found a script to get the group members for an individual group on an individual computer at Powershell.com. But I prefer to use Powershell’s ability to pipeline commands to significantly automate processes so I re-wrote their script in a function:

function Get-GroupMembers()
{
    param(
        [string]$ComputerName = $env:computername,
        [string]$GroupName
    )

    process {
        $QueryPath = 'WinNT://{0}/{1},group' -f $ComputerName, $GroupName
        $exists = $false
        try {
            $exists = [ADSI]::Exists($QueryPath)
        } catch {
            Write-Host
            Write-Error $("Unable to connect to " + $ComputerName + ". " + $_.Exception.Message);
        }

        if ($exists) {
            $group = [ADSI]($QueryPath)
            $members = @()
            $group.Members() |
                ForEach-Object {
                    $AdsPath = $_.GetType().InvokeMember("Adspath", "GetProperty", $null, $_, $null)
                    # Domain members will have an ADSPath like WinNT://<DOMAINNAME>/<USERNAME>
                    # Local members will have an ADSPath like WinNT://<DOMAINNAME>/<COMPUTERNAME>/<USERNAME>
                    $a = $AdsPath.split('/', [StringSplitOptions]::RemoveEmptyEntries)
                    $name = $a[-1]
                    $domain = $a[-2]

                    # determine if member is a 'user' or 'group' object
                    $class = $_.GetType().InvokeMember("Class", "GetProperty", $null, $_, $null)

                    $members += New-Object PSObject -Property @{
                        Name = $name;
                        Domain = $domain;
                        Class = $class;
                        ComputerName = $ComputerName;
                        GroupName = $GroupName;
                    }
            }
            $members
        }
    }
}

Since this function uses Try…Catch syntax for exception handling it will only work in Powershell v2. To use this function to find members of the ‘Administrators’ and ‘Power Users’ groups on a particular host:

('Administrators', 'Power Users') | % { Get-GroupMembers -ComputerName 'YourHost' -GroupName $_ } | format-table

About Brian Wahoff


Brian is the Chief Technology Officer of EPC, Inc. He loves coding, reading, and all things baseball.

Related posts:

  1. Hands-on with Windows 7 Mobile

One Comment


  1. Apr 21, 2011
    11:21 am

    Mike Sweeney

    This is very handy. This will allow us to narrow our search when trying to find security vulns.