powershellactive-directorywindows-10adsipowershell-5.0

Print Local Group Members in PowerShell 5.0


I use the following code to determine members of the local Administrators group:

$obj_group = [ADSI]"WinNT://localhost/Administrators,group"
$members=@($obj_group.Invoke("Members"))|foreach{$_.GetType().InvokeMember("Name","GetProperty",$null,$_,$null)}
Write-Output "Current local Administrators: $members"

This code works in PowerShell 2.0 - 4.0. However, on my Windows 10 machine with PowerShell 5.0, it breaks. For each local account that is a member of the local Administrators group, it throws the following error:

Error while invoking GetType. Could not find member.
At line:2 char:54
+ ... "))|foreach{$_.GetType().InvokeMember("Name","GetProperty",$null,$_,$ ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], MissingMemberException
    + FullyQualifiedErrorId : System.MissingMemberException

For domain accounts that are a member of Administrators, no error is generated.

The thing that puzzles me is GetType() is a member of of the object (I traced out the command by hand), so I am not sure why it errors out.

I looked at the changelog for PowerShell 5.0 and did not see anything that would obviously explain this behavior.

Why is this happening? If there a better way to print members of a local group in PowerShell 5.0?


Solution

  • Ran into this issue myself and figured out a workaround (tested in windows 10 and 8.1)

    $obj_group = [ADSI]"WinNT://localhost/Administrators,group"
    $members= @($obj_group.psbase.Invoke("Members")) | foreach{([ADSI]$_).InvokeGet("Name")}
    Write-Output "Current local Administrators: $members"