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.

FAQs

  • Can the script be used on any Windows machine?
    It’s designed for Windows 7 onwards and Windows Server 2012 onwards.
  • What if Get-LocalUser is unavailable on my system?
    The script automatically resorts to the net.exe user command if Get-LocalUser isn’t available or there’s an architecture mismatch.

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.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver 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

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).