Enforcing user logon restrictions reduces attack surface outside business hours and supports compliance with data access policies. While Active Directory (AD) offers built-in login time restrictions, scripting provides more flexibility. This article will teach you how to use logon scripts to enforce department login time restrictions.
Using logon scripts to enforce login time restrictions across departments
Enforcing login time restrictions consists of four parts: determining the department and allowed login window, creating the script, deploying it using Group Policy, and logging the enforcement status to the Registry. Alternatively, you can set login times via CMD if you’re using AD.
📌 Prerequisites:
- Domain-joined or workgroup Windows 10/11 systems
- Group Policy Editor (or local GPO)
- PowerShell 5.1+ or CMD scripting access
- Admin permissions to apply login scripts via GPO or RMM
📌 Recommended deployment strategies:
| Click to Choose a Method | 💻 Best for Individual Users | 💻💻💻 Best for Enterprises |
| Step 1:Determine the department and the allowed login window | ✓ | |
| Step 2: Create the logon script logic | ✓ | |
| Step 3: Deploy logon script using Group Policy | ✓ | |
| Step 4: Log enforcement status to the Registry | ✓ | |
| Alternative Method: CMD and net user alternatives | ✓ |
Step 1: Determine the department and the allowed login window
The first step to enforcing login time restrictions is to define login windows per department.
📌 Use Case: An IT admin who needs a direct way to map AD department attributes to specific login schedules without manually setting per-user rules
- Press Win, type PowerShell, then click Run as administrator.
- Copy and paste the following code into the prompt, then press Enter:
$allowedTimes = @{
“Sales” = @{Start = 8; End = 18}
“Finance” = @{Start = 7; End = 17}
“IT” = @{Start = 0; End = 23}
“Default” = @{Start = 9; End = 17}
}
To detect the user’s department using an AD attribute, copy and paste the following script instead:
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$department = (Get-ADUser $user.Name -Properties Department).Department
Step 2: Create the logon script logic
Once you’ve defined the login windows, the next step is to create the login script logic.
📌 Use Case: Administrators who want an immediate, customizable restriction script that enforces login hours
- Press Win, type PowerShell, then click Run as administrator.
- Copy and paste the following code into the prompt, then press Enter:
| # Current hour $now = (Get-Date).Hour# Department (fallback to Default if missing) $dept = if ($department) { $department } else { “Default” } if (-not $allowedTimes.ContainsKey($dept)) { $dept = “Default” }# Allowed time window $start = $allowedTimes[$dept].Start $end = $allowedTimes[$dept].End# Check access if ($now -lt $start -or $now -ge $end) { Add-Type -AssemblyName PresentationFramework $startTime = “{0:D2}:00” -f $start $endTime = “{0:D2}:00” -f $end [System.Windows.MessageBox]::Show( “Login not allowed at this time.`nYou may log in between $startTime and $endTime.”, “Access Restricted”, ‘OK’,’Error’ ) # Safer alternative: log off instead of hard shutdown |
⚠️ Warning: Before deploying the settings change on different endpoints, testing it out on a local machine is best. (For more info, refer to: Things to look out for)
Step 3: Deploy logon script using Group Policy
The next step is to deploy the logon script via Group Policy.
📌 Use Case: An IT admin managing multiple endpoints who prefers a scalable, centralized approach to enforce login restrictions across all users
- Press Win + R, type gpmc.msc, then press Enter.
- Navigate the following:
User Configuration > Windows Settings > Scripts (Logon/Logoff)
- Afterward, add the PowerShell script.
- Ensure Execution Policy is set to RemoteSigned by navigating:
Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell > Turn on Script Execution
- Set to: Allow local scripts and remote signed scripts.
Step 4: Log enforcement status to the Registry
Once you’ve enforced the policy, you can record enforcement actions locally using a PowerShell script.
📌 Use Case: IT admins who want to create a local audit trail showing when login restrictions were enforced
- Press Win, type PowerShell, then click Run as administrator.
- Copy and paste the following code into the prompt, then press Enter:
New-Item -Path “HKLM:\SOFTWARE\Org\LogonRestrictions” -Force
Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\LogonRestrictions” -Name “LastEnforced” -Value (Get-Date).ToString(“u”)
Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\LogonRestrictions” -Name “Status” -Value “Login blocked due to after-hours access”
You can then use CMD to check what’s inside your custom registry key.
- Press Win, type cmd, then click Run as administrator.
- Copy and paste the following code into the prompt, then press Enter:
reg query HKLM\SOFTWARE\Org\LogonRestrictions
⚠️ Warning: Ensure you copy and paste the proper script, as incorrect syntax can cause errors. (For more info, refer to: Things to look out for)
Alternative Method: CMD and net user alternatives
This is an alternative way to set login times if you’re using Active Directory.
📌 Use Case: Administrators who want a built-in way to restrict login times without deploying scripts
- Press Win, type cmd, then click Run as administrator.
- Copy and paste the following code into the prompt, then press Enter:
net user username /times:M-F,8am-6pm;Sa-Su,0am-0am
💡 Tip: This setting applies directly at the domain controller level.
⚠️ Note: This method has limitations. For example, it doesn’t provide UI-based enforcement and is not customizable by department unless you separate OU (Organizational Unit) targeting.
⚠️ Things to look out for
| Risks | Potential Consequences | Reversals |
| Not testing on a local machine | Deploying an untested script may cause devices to crash due to issues such as registry key incompatibility. | Apply the changes you want on a local machine, and then verify if the configuration reflects the intended results. |
| Incorrect command syntax | Incorrect command syntax could result in registry corruption, system misbehavior, or the code not doing anything. | Ensure you copy and paste the proper script into the prompt. You may also use apps like PSScriptAnalyzer to check code quality. |
Additional considerations
Specific user scenarios require special handling to prevent accidental lockouts or disruptions. Below are common exceptions you should consider when applying login restrictions.
Break-glass accounts
Break-glass accounts are emergency admin accounts used if the main identity provider is down. Always add an exemption for these accounts by running the following PowerShell script:
if ($user -in $breakGlassAccounts) { return “Bypass restrictions” }
Multiple time zones
Users working in different time zones don’t share the same business hours. If your $allowedTimes assumes UTC+8 but your US staff log in at 9 A.M. their time, they might be denied. You can combat this by converting all checks to UTC and mapping users to their time zone.
Service accounts
Service accounts are non-human accounts used by apps or kiosks. These accounts need 24/7 access, and blocking them may break automations. To handle this, you can put them in a dedicated AD group and add logic to bypass restrictions.
Laptop users
Employees travelling internationally might log in outside their usual office hours, which results in them being denied access. In this scenario, it’s ideal to use AD groups for exceptions or add a script flag to temporarily lift restrictions for specific users.
Troubleshooting common issues
You may encounter issues that affect reliability and user experience when using logon scripts to enforce login restrictions. Below are some frequent problems and how to address them.
Script not executing
Some scripts don’t run during logon or logoff, usually due to accessibility problems and restrictive PowerShell execution policies. To resolve this, you can run Get-ExecutionPolicy and update it with Set-ExecutionPolicy RemoteSigned.
Incorrect department detection
Scripts could misclassify users if AD data is inconsistent. As such, you must check attribute values using PowerShell to confirm department fields are populated by running Get-ADUser -Identity username -Property Department.
Logoff not enforced
Some users stay logged in even if restrictions work at logon, bypassing time-based policies. Consider assigning logoff scripts via Group Policy to enforce session termination when this happens. You can also configure a scheduled task to trigger at fixed times to execute logoffs.
User forcibly rebooted
Some administrators use Stop-Computer to enforce session termination. It’s effective, but the script could result in lost user data due to the forced shutdown or restart.
One alternative is to use logoff.exe instead. This command signs the user out without restarting the device, resulting in less disruption.
NinjaOne services that enhance login time restriction management
MSPs (Managed Services Providers) can enforce and report on time-based access rules across clients without relying on AD or Azure licensing by using NinjaOne.
NinjaOne enhances login time restriction management by:
- Deploying logon restriction scripts remotely across tenants
- Scanning registry keys to confirm policy application per device
- Alerting on login attempts outside policy windows via event or script output
- Tagging endpoints or users who violate login boundaries
- Automating rollback or exception processes for department-specific access
Enforce login boundaries using logon scripts
Controlling login times by departments helps enforce work policies, improve security, and maintain compliance. Implementing these restrictions using logon scripts also reduces the attack surface outside business hours and helps support compliance with data access policies.
Related topics:
- How to Deny Local Sign-In for Users and Groups in Windows 10
- How to Find Failed Login Attempts in Windows Using PowerShell
- How to Allow or Prevent Users from Changing Their Password in Windows 10 & 11
- Enable or Disable Sign in with Picture Password in Windows 10
- How to Enable or Disable the Require Sign-in on Wakeup Setting in Windows 11
