Raphael
Raphael

Reputation: 77

Retrieve local users from local groups in Powershell 4.0

I would like to retrieve all local users from all local groups. I can retrieve all users from all groups of a server machine like this:

Get-CimInstance -ClassName Win32_GroupUser | Select-Object -Property GroupComponent, PartComponent | fl

However I want to limit to local users and groups. I know that if I use Win32_Group and Win32_UserAccount it is possible to add -Filter "LocalAccount='True'" but I don't know how to do it for Win32_GroupUser. I've tried several things and I believe I'm not far but right now I am a bit stuck... My last piece of code was but it returns nothing:

$users=Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='True'" | Select-Object -Property Name
$groups=Get-CimInstance -ClassName Win32_Group -Filter "LocalAccount='True'" | Select-Object -Property Name
ForEach ($group in $groups) {
    ForEach ($user in $users) {
        Get-CimInstance -ClassName Win32_GroupUser | Where-Object {$_.groupcomponent -match 'Win32_Group.Name="$group"' -and $_.partcomponent -match 'Win32_UserAccount.Name="$user"'} | Select-Object -Property GroupComponent, PartComponent | fl
    }
}

My final objective is to put this code in an Ansible playbook and run it in several remote servers. If you have an idea of how to solve this or how to help me I would be grateful.

Upvotes: 1

Views: 2698

Answers (1)

Raphael
Raphael

Reputation: 77

My final solution:

$groups = Get-CimInstance -ClassName Win32_Group -Filter "LocalAccount='True'" | Select-Object -Property Name
ForEach ($group in $groups) {
    $members = $([ADSI]"WinNT://$($env:COMPUTERNAME)/$($group.Name)").members() | % {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
    ForEach ($member in $members) {
        $local = Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='True'" | Select-Object -Property Name | Where-Object Name -eq $member
        if ($local) {"This is the local group: $($group.Name) and this is the local account: $($local.Name)"} else {}
    }
}

This provides a solution to get the local users from the local groups.

Upvotes: 1

Related Questions