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

by raetrace   Last Updated June 12, 2019 07:00 AM

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


Answers 3


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
xXhRQ8sD2L7Z
xXhRQ8sD2L7Z
February 03, 2016 00:19 AM

Much more easier way with WMI

Get-WmiObject -Class win32_useraccount -filter "localaccount=true" | where {$_.disabled -eq $False}
strange walker
strange walker
February 16, 2017 15:11 PM

Starting with Version 5.1 PowerShell also comes with an builtin cmdlet called Get-LocalUser Powershell Local Accounts

Get-LocalUser | Where-Object -Property Enabled -eq True
Rajiv Iyer
Rajiv Iyer
June 12, 2019 06:23 AM

Related Questions


Updated March 27, 2017 12:00 PM

Updated November 17, 2017 11:00 AM

Updated April 11, 2018 09:00 AM

Updated December 04, 2015 06:00 AM

Updated February 02, 2018 07:00 AM