Author Posts

June 24, 2013 at 7:43 am

Hello, I am a PowerShell 3.0 novice and want to add a feature to my first ever production script tool.

The script below will get all local user accounts from remote computers listed in a .txt file then export to .csv format.  How exactly can I incorporate what local groups each local user account is a member of?  For each local user account retrieved I want to list what local groups it is a member of.

get-ciminstance -classname win32_useraccount -filter "localaccount='true'" -computername (get-content C:\PS\.txt) | export-csv c:\PS\_localuseraccounts.csv (export to .csv)

Your insight is greatly appreciated,

Matt, PS 3.0 novice

June 24, 2013 at 1:17 pm

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 answer your question 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

Alternatively pipe straight into you CSV

June 25, 2013 at 12:21 pm

Thanks Richard.  I apologize in advance for stupid questions for I am a PowerShell (and scripting in general) novice. 

I tried to copy & paste into PS3 ISE the script you provided and it does not work.  What am I doing wrong?  As you can see from attached picture of my ISE, when running the selection of get-ciminstance... it works.  Maybe I am out of my depth in this forum.

Another Q: I notice you do it -filter "LocalAccount = $true".  Is there a difference between that and “localaccount=’true’” ?