Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
myron-semack Avatar asked Aug 11 '15 18:08

myron-semack


1 Answers

Nice! Needed this!

The .net way was also a bypass:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$computer =  $env:COMPUTERNAME
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, $computer
$idtype = [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName
$group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, $idtype, 'Administrators')
$group.Members |  select @{N='Server'; E={$computer}}, @{N='Domain'; E={$_.Context.Name}}, samaccountName
like image 194
mendel Avatar answered Oct 13 '22 03:10

mendel