This PowerShell script audits local user accounts by listing each account’s enabled/disabled status and extracting detailed last logon information using the net user
command. It outputs a neatly formatted table, providing system administrators with a clear snapshot of user account activity for easier monitoring and troubleshooting.
Click to view script…
<#
.SYNOPSIS
Audits local user accounts by listing their enabled/disabled status and last logon time.
.DESCRIPTION
This script retrieves local user accounts using Get-LocalUser and then obtains last logon information
for each account by parsing the output of the "net user" command. It outputs a table showing each account's name,
whether it is enabled, and its last logon time (or "Never" if the account has not logged on).
.NOTES
Run as Administrator if necessary.
#>
function Get-LastLogonNetUser {
param (
[Parameter(Mandatory = $true)]
[string]$UserName
)
# Execute the "net user" command for the given user
$netUserOutput = net user $UserName 2>&1
# Look for a line that contains "Last logon"
$lastLogonLine = $netUserOutput | Where-Object { $_ -match "Last logon" }
if ($lastLogonLine) {
# The expected format is something like:
# Last logon 2/12/2021 3:45:30 PM
# Remove the label text and trim spaces to isolate the date/time string.
$logonValue = ($lastLogonLine -replace ".*Last logon\s+", "").Trim()
if ($logonValue -match "Never") {
return "Never"
}
else {
# Attempt to parse the logon value as a DateTime.
try {
$dt = [DateTime]::Parse($logonValue)
return $dt
}
catch {
return $logonValue
}
}
}
else {
return "Unknown"
}
}
# Retrieve local user accounts.
try {
$localUsers = Get-LocalUser
} catch {
Write-Error "Failed to retrieve local users. Ensure this is run on a supported version of Windows with appropriate permissions."
exit
}
# Prepare an array to store the audit results.
$result = @()
foreach ($user in $localUsers) {
$userName = $user.Name
$lastLogon = Get-LastLogonNetUser -UserName $userName
$result += [PSCustomObject]@{
Name = $userName
Enabled = $user.Enabled
LastLogon = $lastLogon
}
}
# Output the results in a formatted table.
$result | Format-Table -AutoSize