This PowerShell Script shows how to set active directory user’s logon time.
Sometimes IT admins want to set the user account logon hours to restrict user logon time. This script can help to do it.
Step1: Run the script in the Windows PowerShell Console, type the one command: Import-Module <Script Path> at the prompt.
For example, type Import-Module C:\Script\ SetADUserLogonTime.psm1
This is shown in the following figure.
Step 2: You can type the command Get-Help
Set-OSCLogonHours -Full to display the entire help file for this function, such as the syntax, parameters, or examples.

Here are some code snippets for your reference.
#Assign logon binary value to 'Logonhours' attribute.
If($SamAccountName)
{
Foreach($User in $SamAccountName)
{
Get-ADUser -Identity $User | Set-ADUser -Replace @{Logonhours = [Byte[]]$HourBinary}
Write-Host "Successfully set user '$User' logon time."
}
}
If($CsvFilePath)
{
If(Test-Path -Path $CsvFilePath)
{
#import the csv file and store in a variable
$Names = (Import-Csv -Path $CsvFilePath).SamAccountName
Foreach($Name in $Names)
{
Get-ADUser -Identity $Name | Set-ADUser -Replace @{Logonhours = [Byte[]]$HourBinary}
Write-Host "Successfully set user '$Name' logon time."
}
}
Else
{
Write-Warning "Cannot find path '$CsvFilePath', because it does not exist."
}
}
#Assign logon binary value to 'Logonhours' attribute. If($SamAccountName) { Foreach($User in $SamAccountName) { Get-ADUser -Identity $User | Set-ADUser -Replace @{Logonhours = [Byte[]]$HourBinary} Write-Host "Successfully set user '$User' logon time."}} If($CsvFilePath) { If(Test-Path -Path $CsvFilePath) { #import the csv file and store in a variable $Names = (Import-Csv -Path $CsvFilePath).SamAccountName Foreach($Name in $Names) { Get-ADUser -Identity $Name | Set-ADUser -Replace @{Logonhours = [Byte[]]$HourBinary} Write-Host "Successfully set user '$Name' logon time."}} Else { Write-Warning "Cannot find path '$CsvFilePath', because it does not exist."}}
Note
This script must be running on “Pacific Standard Time” time zone environment. Otherwise, the time settings may not very accurate.
Example 1: Type Set-OSCLogonHours -SamAccountName doris,katrina -DayofWeek Monday,Saturday -From 6AM -To 7PM
command in the Windows PowerShell Console.
This command will set user's logon time attributes.
Example 2: Type Set-OSCLogonHours -CsvFilePath C:\Script\SamAccountName.csv -DayofWeek Wednesday,Friday -From 7AM -To 8PM command in the Windows PowerShell Console.
![]()
This command will set user's logon time attributes based on imported user list.
Note: the CSV File format must follow the format below:

Windows PowerShell 2.0