Back to Resources
Level
Script
Security
This script tackles the issue of lingering or unauthorized local user accounts on Windows machines by providing a simple, automated way to disable or delete them, ultimately tightening security and preventing accidental or intentional misuse of overlooked user profiles.
It uses a string of comma-separated usernames supplied through a Level script variable, converting them into an array for sequential processing. For each user, the script checks whether the account exists, then disables it by default to prevent login attempts. A simple uncommented line can switch the behavior from disabling to permanently removing the user account, granting administrators a flexible way to handle unauthorized or unneeded users. By running under System-level permissions, it ensures minimal manual intervention and reduces friction in day-to-day security operations.
1<#
2This resource is provided as a convenience for Level users. We cannot
3guarantee it will work in all environments. Please test before deploying
4to your production environment. We welcome contributions to our community
5library
6
7Level Library
8https://level.io/library/script-windows-delete-disable-users
9#>
10
11# Split the string into an array
12$userArray = "{{UsersToDelete}}" -split ',' | ForEach-Object { $_.Trim() }
13
14foreach ($user in $userArray) {
15 # Check if the user exists (assuming we're looking for local users by username)
16 if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) {
17 try {
18 # Disable the user account
19 Disable-LocalUser -Name $user
20 Write-Output "User $user has been disabled."
21
22 # Commented out: To delete instead of disable, uncomment the next line
23 # Remove-LocalUser -Name $user
24 # Write-Output "User $user has been deleted."
25 }
26 catch {
27 # Use double quotes with escaping for the colon
28 Write-Error "Failed to disable user $user`: $_"
29 }
30 } else {
31 Write-Output "User $user does not exist."
32 }
33}
Windows - Delete/Disable Users
This PowerShell script processes a comma-separated list of usernames provided through Level's script variables to perform account disablement on Windows systems. For each username in the list, it verifies the account exists locally, then attempts to disable it (with commented code available for deletion instead). The script provides status messages for each attempted operation, including success confirmations and error details if the operation fails or if the specified user doesn't exist.
PowerShell
100
Local system
Explore more automations, scripts, and policies to further enhance your IT operations.