Using PowerShell to List Local Users on Windows Systems

PowerShell is a potent tool in the arsenal of IT professionals, often leveraged for its ability to automate tasks and extract data seamlessly. One critical task frequently encountered by Managed Service Providers (MSPs) and system administrators is listing users on a computer system. Today, we delve into a PowerShell script designed specifically for this: to list local users. 

Background

There’s no denying that in today’s fast-paced IT environment, the ability to quickly extract data about system users is invaluable. This is particularly true in large enterprises or whenever new equipment or software is being rolled out. System administrators and MSPs often find themselves needing to understand who has access to what and when. The provided PowerShell script fulfills this need by listing local users on a Windows machine, allowing professionals to gain insights quickly.

The Script

#Requires -Version 2.0

<#
.SYNOPSIS
    Lists local computers' users.
.DESCRIPTION
    Lists local computers' users. By default it lists only the enabled users.
.EXAMPLE
    No parameters needed.
    Lists enabled users on the local computer.
.EXAMPLE
     -AllUsers
    Lists enabled and disabled users on the local computer.
.EXAMPLE
    PS C:> List-Users.ps1 -AllUsers
    Lists enabled and disabled users on the local computer.
.OUTPUTS
    System.Management.Automation.SecurityAccountsManager.LocalUser[]
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012
    Release Notes:
    Initial Release
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    # Will return disabled users as well as enabled users
    [Switch]
    $AllUsers
)

begin {
    Write-Output "Starting List Users"
}

process {
    # If we are running powershell under a 32bit OS or running a 32bit version of powershell
    # or we don't have access to Get-LocalUser
    if (
        [Environment]::Is64BitProcess -ne [Environment]::Is64BitOperatingSystem -or
            (Get-Command -Name "Get-LocalUser" -ErrorAction SilentlyContinue).Count -eq 0
    ) {
        # Get users from net.exe user
        $Data = $(net.exe user) | Select-Object -Skip 4
        # Check if the command ran the way we wanted and the exit code is 0
        if ($($Data | Select-Object -last 2 | Select-Object -First 1) -like "*The command completed successfully.*" -and $LASTEXITCODE -eq 0) {
            # Process the output and get only the users
            $Users = $Data[0..($Data.Count - 3)] -split 's+' | Where-Object { -not $([String]::IsNullOrEmpty($_) -or [String]::IsNullOrWhiteSpace($_)) }
            # Loop through each user
            $Users | ForEach-Object {
                # Get the Account active property look for a Yes
                $Enabled = $(net.exe user $_) | Where-Object {
                    $_ -like "Account active*" -and
                    $($_ -split 's+' | Select-Object -Last 1) -like "Yes"
                }
                # Output Name and Enabled almost like how Get-LocalUser displays it's data
                [PSCustomObject]@{
                    Name    = $_
                    Enabled = if ($Enabled -like "*Yes*") { $true }else { $false }
                }
            } | Where-Object { if ($AllUsers) { $_.Enabled }else { $true } }
        }
        else {
            exit 1
        }
    }
    else {
        try {
            if ($AllUsers) {
                Get-LocalUser
            }
            else {
                Get-LocalUser | Where-Object { $_.Enabled -eq $true }
            }
        }
        catch {
            Write-Error $_
            exit 1
        }
    }
}

end {
    Write-Output "Completed List Users"
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

At its core, the script is fairly straightforward. It begins by defining a parameter, $AllUsers, which when invoked, includes both enabled and disabled users in its output. In the ‘process’ block, the script first checks the system’s architecture and the availability of the Get-LocalUser cmdlet. If there’s a mismatch or the cmdlet is unavailable, it falls back to using the legacy net.exe user command. The data derived from either method is then processed to list the users. When the net.exe user command is utilized, the script fetches user status, checking whether each account is active. It then outputs this data in a structured manner. In scenarios where Get-LocalUser is available, it fetches and lists the users directly, filtering only the enabled ones unless the $AllUsers parameter is invoked.

Potential Use Cases

Imagine an IT professional, Jane, rolling out a new software update across her company. Before deploying the update, she needs to verify the user accounts on each machine to ensure that all software licenses are correctly assigned. Instead of manually checking each computer, she employs the PowerShell script, saving hours of her valuable time.

Comparisons

While the script utilizes the Get-LocalUser cmdlet where possible, its alternative approach using net.exe user is a nod to legacy systems. Some other scripts might rely solely on newer cmdlets or methods. The provided script’s dual approach ensures compatibility across a broad range of Windows systems, making it versatile in diverse environments.

Implications

A list of users on a computer can provide a snapshot of potential access points for unauthorized personnel. In the context of IT security, understanding these users and their statuses is a foundational step in ensuring that only authorized individuals have access.

Recommendations

  • Regularly update your PowerShell to have access to the latest cmdlets.
  • Always run scripts from trusted sources to ensure system security.
  • Regularly audit user lists to ensure unauthorized accounts haven’t been added.

Final thoughts

NinjaOne, with its robust IT management solutions, complements tools like this PowerShell script. When IT professionals list local users using our PowerShell script, they can then utilize NinjaOne’s comprehensive platform to manage, monitor, and secure these users, ensuring that IT infrastructure remains both optimized and secure.

FAQs

It’s designed for Windows 7 onwards and Windows Server 2012 onwards.

The script automatically resorts to the net.exe user command if Get-LocalUser isn’t available or there’s an architecture mismatch.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service delivery tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like