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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With