3

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?

stackprotector
  • 10,498
  • 4
  • 35
  • 64
Help
  • 161
  • 1
  • 2
  • 14
  • If you're domain-joined then your query will attempt to query the domain users and groups, as will the `GetRelated()` method. That's a notorious performance bottleneck. You can try to filter it to just the local account with `Get-WmiObject -ClassName Win32_Group -Filter "Name='Administrators' and Domain='$env:computername'"` but I think `GetRelated()` will do the same thing. I don't recall if `$env:computername` works on PSv2, but it's just the hostname. – Bacon Bits Apr 19 '21 at 17:31
  • You are correct, that command also queries domain users! I have tried to test your recommendation to query local users only, however, I have not been successful, the command seems to only list the group name and it does not list its user members, have I done something wrong? Get-WmiObject -ClassName Win32_Group -Filter "Name='Administrators' and Domain='$env:computername'" | select Name – Help Apr 21 '21 at 14:54

1 Answers1

1

Tuning

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.

Different approaches

  1. 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
    
  2. 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.

stackprotector
  • 10,498
  • 4
  • 35
  • 64