WMI association example

A question came up on the Powershell.org forum about finding the groups of which  local accounts are members

You can get account data using Win32_UserAccount

Group information is held in Win32_Group. You can see the relationship between users and groups by dumping the Win32_GroupUser instances. You will see a load of entries like this

GroupComponent : Win32_Group (Name = “Administrators”, Domain = “RSLAPTOP01″)
PartComponent : Win32_UserAccount (Name = “Administrator”, Domain = “RSLAPTOP01″)
PSComputerName : CimClass : root/cimv2:Win32_GroupUser
CimInstanceProperties : {GroupComponent, PartComponent}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties

WMI classes have associations – in this case there is an association between the Win32_User and the Win32_Group classes. The Win32_GroupUser can be thought of as the linking class. What we need to do to is to go from the individual instances of Win32_User (the users) to the associated groups.

Something like this should do it

$data = Get-CimInstance -ClassName Win32_UserAccount -Filter “LocalAccount = $true” |
foreach {
$groups = Get-CimAssociatedInstance -InputObject $PSItem -ResultClassName Win32_Group | select -ExpandProperty Name
$PSItem | Add-Member -MemberType NoteProperty -Name “Groups” -Value ($groups -join “;”) -PassThru
$data | select Caption, Groups

WMI – a bit convoluted but it always gets there

This entry was posted in PowerShell and WMI. Bookmark the permalink.

One Response to WMI association example

  1. Richard,

    Nice, very nice – showing users belonging to which groups.
    How about inverting the output to show – for each unique group – which id’s are in which groups?

    Seems like someone could parse each group because of the delimiting ‘;’ semicolon, but then looks like building some kind of hash table to load and dump it would be the order of execution.

    I know you have your direction, but I thought I’d ask if you had any thoughts on it –
    You’ve been busy, haven’t seen any writing lately. Must be from your AD publishing?

    Dave C.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s