Back to Resources

Level Verified

Windows Lock Device Script

Created by

Level

Type

Script

Category

Security

Platforms
WindowsApple iOSLinux

Problem Overview

When critical security incidents occur or a device falls into the wrong hands, administrators need an immediate way to ensure no one can log into or remain logged on to that system. This script addresses that challenge by instantly logging out active sessions and disabling local or domain accounts, delivering peace of mind in high-pressure circumstances.

Description

This script forcefully logs out all currently active user sessions on a Windows system. It then disables every local user account to prevent any subsequent logins. If the device is domain-joined, it also attempts to disable Active Directory user accounts by connecting to the relevant domain environment, ensuring a comprehensive lock on all potential user access points.

Script

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-lock-device
9#>
10
11# We use a script-scoped variable so that all functions can modify it.
12# Initialize $script:errors to $false at the start.
13$script:errors = $false
14
15# Function to check if the device is domain-joined
16function Is-DomainJoined {
17    $domain = (Get-WmiObject Win32_ComputerSystem).PartOfDomain
18    return $domain
19}
20
21# Function to log out all users
22function LogOut-Users {
23    try {
24        $sessions = query session 2>$null | ForEach-Object {
25            $fields = $_ -split '\s{2,}'
26            if ($fields.Count -ge 3) {
27                [PSCustomObject]@{
28                    SessionName = $fields[0]
29                    UserName = $fields[1]
30                    SessionID = $fields[2]
31                }
32            }
33        }
34
35        foreach ($session in $sessions) {
36            if ($session.UserName -and $session.SessionID -match '^\d+$') {
37                try {
38                    logoff $session.SessionID
39                    Write-Host "User $($session.UserName) has been logged out."
40                } catch {
41                    Write-Host "ALERT: Failed to log out user $($session.UserName): $_"
42                    $script:errors = $true
43                }
44            }
45        }
46    } catch {
47        Write-Host "ALERT: Error retrieving user sessions: $_"
48        $script:errors = $true
49    }
50}
51
52# Function to disable all local accounts
53function Disable-LocalAccounts {
54    try {
55        $localUsers = Get-LocalUser
56        foreach ($user in $localUsers) {
57            try {
58                Disable-LocalUser -Name $user.Name
59                Write-Host "Local account $($user.Name) has been locked."
60            } catch {
61                Write-Host "ALERT: Failed to lock local account $($user.Name): $_"
62                $script:errors = $true
63            }
64        }
65    } catch {
66        Write-Host "ALERT: Error retrieving local accounts: $_"
67        $script:errors = $true
68    }
69}
70
71# Function to disable Active Directory accounts (only if domain-joined)
72function Disable-ADAccounts {
73    try {
74        $adUsers = Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty UserName
75        if ($adUsers -and $adUsers -match '\\') {
76            foreach ($adUser in $adUsers) {
77                try {
78                    # Extract just the username (DOMAIN\Username format)
79                    $adUserName = $adUser -split '\\' | Select-Object -Last 1
80                    Disable-ADAccount -Identity $adUserName -Confirm:$false
81                    Write-Host "AD account $adUserName has been locked."
82                } catch {
83                    Write-Host "ALERT: Failed to lock AD account $($adUserName): $($_.Exception.Message)"
84                    $script:errors = $true
85                }
86            }
87        }
88    } catch {
89        Write-Host "ALERT: Failed to retrieve AD users: $_"
90        $script:errors = $true
91    }
92}
93
94# Execute actions
95LogOut-Users
96Disable-LocalAccounts
97
98# If the system is domain-joined, disable AD users
99if (Is-DomainJoined) {
100    Write-Host "Domain detected. Locking AD users..."
101    Disable-ADAccounts
102} else {
103    Write-Host "No domain detected. Skipping AD account lock."
104}
105
106if ($script:errors) {
107    Write-Host "ALERT: Errors occurred during execution. Exiting with code 1."
108    exit 1
109}
110
111Write-Host "All users have been logged out and locked successfully."
112

Use Cases

  • Urgent lockdown for lost or stolen devices
  • Quick response to a suspected security breach
  • Regulatory or compliance requirement for secure device decommissioning
  • Rapid removal of access for recently terminated employees

Recommendations

  • Test thoroughly in a non-production environment before widespread deployment
  • Consider building a script-based monitor in Level to trigger this script on demand when a security alert occurs
  • For scheduled security routines, set up a recurring automation in Level with a schedule trigger to run this script
  • Review all locked accounts afterward to ensure legitimate users retain appropriate access in non-emergency scenarios

FAQ

  • Does this script require admin privileges?
    Yes, it must run with administrative permissions to log out sessions and modify accounts. Level executes scripts at system or root level by default.
  • What happens if the device is not domain-joined?
    The script skips the domain user lockout steps and only locks local accounts.
  • Will this script affect system processes?
    No, it only targets user sessions and accounts, leaving essential system processes untouched.
  • How can I confirm it worked correctly?
    Review the script output in the Level console for any error messages and confirm users are no longer able to log in.
  • Can this process be reversed automatically?
    Yes. See our Windows Unlock Device Script.

Included with this Script:

Below is a list of what you can expect to find when importing this Script.

Script details:

The following data and settings will be imported with your script.

Script Name

Windows - Lock Device

Description

This script logs out all active users and disables all local accounts on a system. If the device is domain-joined, it also disables Active Directory accounts.

Language

PowerShell

Timeout (In Seconds)

100

Run As

Local system

Import into Level

Related resources

Explore more automations, scripts, and policies to further enhance your IT operations.

View all resources