Last active
March 23, 2022 18:52
-
-
Save RobBiddle/1444c7e548609080873f16ab9eb95461 to your computer and use it in GitHub Desktop.
PowerShell function to Get Windows Local Group Members via WMI - Returns a PSObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-WMILocalGroupMember { | |
[CmdletBinding()] | |
[OutputType([PSObject])] | |
param ( | |
[Parameter()] | |
[String] | |
$ComputerName = $env:computername, | |
[Parameter()] | |
[String] | |
$GroupName | |
) | |
$localGroups = get-wmiobject win32_Group -Filter "LocalAccount = 'True'" | |
if ($GroupName) { | |
$localGroups = $localGroups | Where-Object Name -eq $GroupName | |
} | |
$output = foreach ($group in $localGroups) { | |
$localGroupMembers = Get-WmiObject -Class Win32_GroupUser -Filter "GroupComponent=""Win32_Group.Domain='$ComputerName',Name='$($group.Name)'""" -ComputerName $ComputerName | |
$parsedLocalGroupMembers = $localGroupMembers | ForEach-Object { | |
$_.partcomponent -match ".+Domain\=(.+)\,Name\=(.+)$" > $nul | |
[PSCustomObject] @{ | |
User = $matches[1].trim('"') + "\" + $matches[2].trim('"') | |
UserDomain = $matches[1].trim('"') | |
UserName = $matches[2].trim('"') | |
} | |
} | |
foreach ($member in $parsedLocalGroupMembers) { | |
[PSCustomObject] @{ | |
ComputerName = $ComputerName | |
GroupName = $group.Name | |
GroupDomain = $group.Domain | |
GroupSID = $group.SID | |
User = $member.User | |
UserDomain = $member.UserDomain | |
UserName = $member.UserName | |
} | |
} | |
} | |
return $output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed so that when run on a Domain Computer only Local Groups are queried.