Friday fun: Find all local groups and their members

Without my favourite tool (PowerShell) in a pure DOS command prompt, this is how I’d have displayed the groups and their members:

for /f "tokens=1,* delims=*" %i in ('net localgroup ^| findstr /R /C:"^\*" ') do @ (echo.&echo Group:%i&echo. & for /f "tokens=* skip=6" %z in ( 'net localgroup "%i" ^| findstr /v /C:"The command completed successfully."') do @ echo %z)

When mixing the native DOS command and some PowerShell regular expression, this is how I’d get the same result displayed:

(net localgroup) -match "^\*" -replace "\*","" | foreach { 
    "`nGroup:$($_)`n" ; 
    (net localgroup "$_") | Select-String -Pattern "^\-","^The\sCommand","^Alias\sname","^Comment","^Members","^(\S)?$" -notmatch

If I had to achieve the same task only in PowerShell without calling native DOS commands, I’d do:

([ADSI]"WinNT://$($env:computername),computer").psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | foreach {
    ([ADSI]$_.psbase.Path).psbase.Invoke("Members") | foreach {
        $_.GetType().InvokeMember("Name",'GetProperty',$null,$_, $null)

Note that I’ve adapted the above code from PowerShell MVP Shay Levy that can be found on this page

I’ve modified his code because the following syntax (the children enumeration actually) falls in an infinite loop on my windows 8.1

$computer = [ADSI]"WinNT://$server,computer"

There are other annoyances. If I launch the following as a standard user it works


…but I get the following errors at the end of the enumeration:
format-default : The following exception occurred while retrieving members: “Unknown error (0x80005004)”
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMembers,Microsoft.PowerShell.Commands.FormatDefaultCommand

…and I don’t get the above error with Powershell running as Admin.

I wonder why all WinNT ADsPath don’t work in with the [ADSI], alias the System.DirectoryServices.DirectoryEntry .Net class.

2 thoughts on “Friday fun: Find all local groups and their members

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.