PowerShell: How to get local users and local groups, but exclude disabled accounts

localpowershellusers

I got a PowerShell command that gives me a list of users and the groups those users are members of. The only problem is that is gives me every user including those that are disabled. I need to be able to list just the active users and their respective groups. Any help would be appreciated.

$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | Foreach-Object {    $groups = $_.Groups() | Foreach-Object {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)} ; $_ | Select-Object @{n='UserName';e={$_.Name}},@{n='Groups';e={$groups -join ';'}} } | Format-Table -autosize -wrap

Best Answer

You might use a WMI query to get AccountType (512 = Enabled, 514 = Disabled):

Edit: there are other flags which indicate enabled accounts, but the basic enabled/disabled is 512/514. Refer to this list.

Third try:

Function Check-Enabled ($Username) {
   -not (Get-WmiObject Win32_UserAccount -filter "LocalAccount=True AND Name='$Username'").disabled
}

Then add the property to your Select-Object. I also formatted it for my own readability, but still the same code:

$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | where { $_.SchemaClassName -eq 'user' } | Foreach-Object {
   $groups = $_.Groups() | Foreach-Object {
      $_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)
   }
   $_ | Select-Object @{n='UserName';e={$_.Name}},
                      @{n='Groups';e={$groups -join ';'}},
                      @{n='Enabled';e={Check-Enabled $_.Name}}
} | Format-Table -autosize -wrap