Problem overview
This script tackles the often-overlooked issue of unauthorized local administrators on Windows endpoints by automatically detecting any admin accounts that are not officially approved, preventing security gaps that can arise from unnoticed privileged users.
<#
This resource is provided as a convenience for Level users. We cannot
guarantee it will work in all environments. Please test before deploying
to your production environment. We welcome contributions to our community
library
Level Library
https://level.io/library/script-windows-unauthorized-admins
#>
$AuthorizedAdmins = "{{cf_authorized_admins}}"
# Get all local admins that are enabled
$admins = Get-LocalGroupMember -Group "Administrators" |
Where-Object { $_.ObjectClass -eq 'User' -and (Get-LocalUser $_.SID).Enabled -eq $true } |
Select-Object -ExpandProperty Name
# Extract just the username by splitting on '\' and taking the last part
$admins = $admins | ForEach-Object { ($_ -split '\\')[-1] }
$detectedAdmins = $admins -join ","
# Join the usernames into a single string separated by commas
$detectedArray = $detectedAdmins -split ',' | ForEach-Object { $_.Trim().ToLower() }
$authorizedArray = $AuthorizedAdmins -split ',' | ForEach-Object { $_.Trim().ToLower() }
# Find admins in detected list but not in authorized list
# Convert both to lowercase for case-insensitive comparison
$unauthorizedAdmins = $detectedArray | Where-Object { $authorizedArray -notcontains $_ }
# Output unauthorized admins separated by commas
$unauthorizedString = $unauthorizedAdmins -join ','
if ($unauthorizedAdmins.Count -gt 0) {
Write-Output "Unauthorized Admins ALERT: $unauthorizedString"
exit 1
} else {
Write-Output "No unauthorized admins detected."
exit 0
} It leverages Level script variables (such as “DetectedAdmins”) alongside custom fields (for example, “AuthorizedAdmins”) to cross-check active Windows admin accounts against your organization’s sanctioned admin list. If any unapproved user is found, the script flags and reports them, then exits with an error code to trigger alerts or additional actions through Level. By integrating with a script-based monitor, you can seamlessly generate notifications whenever an unauthorized admin appears.
Use cases
- Monitoring newly added admin accounts without proper authorization
- Enforcing least privilege policies and compliance requirements
- Automating security checks to reduce manual oversight
- Integrating into broader admin compliance automation workflows
Recommendations
- Pair this script with a script-based monitor in Level to automatically flag suspicious admin additions in real time
- Configure an automated schedule in Level to run ongoing compliance checks, ensuring no unauthorized accounts linger
- Always test in a non-production environment to confirm correct output and error codes
- Maintain an up-to-date authorized admin list in Level’s custom fields to ensure accurate comparisons