I've crafted the command below which listed out the members of a group:
gwmi win32_group -filter 'Name="Administrators"'|%{$_.GetRelated('Win32_UserAccount')} | select Name
The command above works, however, it takes ages to complete, is there a way of fine-tuning the command above so it runs faster?
Please note, I am limited to PowerShell 2.0.
Edit: Seems like the command above is also querying all DC accounts. How do I only query local users?
The slow part in your pipeline is the call of .GetRelated()
, because this will evaluate the associations of WMI class instances, which may be huge lists. So you have to be careful and filter as much as possible. You can do it like this:
(Get-WmiObject -Class Win32_Group -Filter "LocalAccount = TRUE and SID = 'S-1-5-32-544'").GetRelated("Win32_Account", "Win32_GroupUser", "", "", "PartComponent", "GroupComponent", $false, $null) | Select-Object -Property Name
Note, that I used the well-known SID of the Administrators group to look for it, because its name may differ in other languages. I also queried for Win32_Account
instead of Win32_UserAccount
to really return ALL members of the Administrators group which may include other groups and not only user accounts. You may change this according to your needs of course. You can read more about this tuning in this article.
Another approach would be to define everything in one WMI query:
Get-WmiObject -Query "ASSOCIATORS OF {Win32_Group.Domain='$env:COMPUTERNAME',Name='Administrators'} WHERE AssocClass=Win32_GroupUser ResultRole=PartComponent" | Select-Object -Property Name
Further more, you can use the net
tool to query the members of the Administrators group:
net localgroup Administrators
Drawback: You have to parse the textual output.