How to Automatically Lock Windows After Inactivity Using PowerShell

Locking a computer after a period of inactivity is an essential security measure that every IT professional acknowledges. Especially in shared or public environments, this ensures that an unattended workstation does not become an open door for malicious activities. PowerShell, the backbone of many IT operations in Windows environments, provides a versatile way of setting an inactivity timeout. 

Background

Inactivity timeouts aren’t just about security, they’re also about resource management. IT professionals and Managed Service Providers (MSPs) often implement these features to save power, reduce wear on hardware, and as an initial layer of security. The script provided dives deep into the realm of automating this process, allowing for a set-it-and-forget-it approach.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Set the Inactivity(Lock Computer) timeout time if it already isn't set.
.DESCRIPTION
    Set the Inactivity(Lock Computer) timeout time if it already isn't set.
    Can be set regardless if the -Force parameter is used.
.EXAMPLE
     -Minutes 5
    This set the Inactivity(Lock Computer) timeout to 5 minutes, does not change if already set.
.EXAMPLE
     -Minutes 5 -Force
    This set the Inactivity(Lock Computer) timeout to 5 minutes, and forces the change if already set.
.EXAMPLE
    PS C:> Set-IdleLock.ps1 -Minutes 5
    This set the Inactivity(Lock Computer) timeout to 5 minutes
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes: Renamed script and added Script Variable support, updated Set-ItemProp
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/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 or website 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).
.COMPONENT
    LocalUserAccountManagement
#>

[CmdletBinding()]
param (
    [Parameter()]
    [int]$Minutes,
    [switch]$Force = [System.Convert]::ToBoolean($env:force)
)

begin {
    if ($env:minutes -and $env:minutes -notlike "null") {
        $Minutes = $env:minutes
    }
    
    if(-not ($Minutes)){
        Write-Error "Minutes is required!"
        exit 1
    }

    if($Minutes -gt 9999 -or $Minutes -lt 0){
        Write-Error "Minutes must be between 0 and 9999 (including 0 and 9999)."
        exit 1
    }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        # Do not output errors and continue
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = Get-ItemProperty -Path $Path -Name $Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "$Path$Name changed from $CurrentValue to $(Get-ItemProperty -Path $Path -Name $Name)"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "Set $Path$Name to $(Get-ItemProperty -Path $Path -Name $Name)"
        }
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    
    $Path = "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem"
    $IdleName = "InactivityTimeoutSecs"
    $Seconds = $Minutes * 60
    # Override "Check if already set"
    if (-not $Force) {
        # Check if already set
        if ($(Get-ItemProperty -Path $Path | Select-Object -Property $IdleName -ExpandProperty $IdleName -ErrorAction SilentlyContinue)) {
            $CurrentIdleSeconds = $(Get-ItemPropertyValue -Path $Path -Name $IdleName)
            # If value already set, do nothing.
            if ($CurrentIdleSeconds) { exit 0 }
        }
    }

    # Sets InactivityTimeoutSecs to $Minutes
    try {
        Set-ItemProp -Path $Path -Name $IdleName -Value $Seconds
        Write-Host "Set the Inactivity to $($Seconds/60) minutes."
    }
    catch {
        Write-Error $_
        exit 1
    }
}
end {
    
    
    
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

This PowerShell script aims to set the inactivity timeout on Windows. Here’s how it works:

  • Prerequisites: The script starts by mentioning that it requires at least version 5.1 of PowerShell.
  • Parameters: Two parameters are set – $Minutes, which is mandatory and denotes the duration after which the computer should lock, and $Force which, when used, forces the inactivity timeout even if already set.

Functions:

  • Test-IsElevated: Checks if the script is run with administrator privileges.
  • Set-ItemProp: Handles the creation or modification of the registry key.

Process Block:

  • Initial Check: Verifies the user has the necessary privileges.
  • Registry Path: Directs to the location where the inactivity timeout is set.
  • Condition Check: If the -Force switch isn’t used, it checks if the timeout is already set. If set, it exits without making changes.
  • Setting Timeout: If conditions pass, the inactivity timeout is set or changed.

Potential Use Cases

Imagine working in a university’s public computer lab. Multiple students use these computers throughout the day. To ensure each student’s work remains confidential, the IT department could utilize this script. By setting an inactivity timeout of, say, 5 minutes, they ensure that if a student forgets to log out, the system automatically locks, preventing unauthorized access.

Comparisons

While there are GUI methods to set inactivity timeouts, such as through the Windows Control Panel, this script provides an advantage in scalability. For massive deployments across numerous computers, using a script like this is more efficient. Additionally, other methods might involve Group Policy settings, but they lack the granularity and quick application that a PowerShell script can offer.

FAQs

  • Why use PowerShell for this task?
    PowerShell allows for automation, scalability, and quick deployment, especially across multiple systems.
  • Is admin privilege always required?
    Yes, to modify system settings like inactivity timeouts, administrator privileges are essential.
  • Can the timeout be set for more extended periods?
    This script allows setting the timeout for up to 9999 minutes, but it’s essential to strike a balance between usability and security.

Implications

While the immediate purpose is to enhance security, the wrong inactivity timeout can disrupt work, especially if set too short. On the flip side, too long a timeout might compromise security. Moreover, inactivity settings become critical in high-security environments, where leaving a terminal unlocked could have grave consequences.

Recommendations

  • Test Before Applying: Always run scripts in a test environment before deploying widely.
  • Balance Security with Usability: While shorter timeouts are more secure, they shouldn’t hinder daily tasks.
  • Stay Updated: Periodically review and adjust the inactivity timeouts as per organizational needs.

Final Thoughts

NinjaOne offers a comprehensive IT monitoring and management solution, and when integrated with scripts like this, it provides robust control over an IT environment. Whether you’re looking to set inactivity timeouts or manage other aspects of IT infrastructure, NinjaOne remains a reliable partner for efficient, secure, and optimized operations.

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

Watch Demo×
×

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).