Deploy Logon Hours via PowerShell

## Title:			setlogonhours.ps1
## Description:		Deploy logon time restrictions individually based on group membership.
## Author:			Steven J. Borrelli
## Email:			sborrelli@rdata.us
## Date:			20180629
## Version:			1.01

# First things first
  Import-Module ActiveDirectory
if (-not (Get-Module ActiveDirectory)){
}

# Specify the AD Security Groups to use
$group1 = "LogonHrs1"
$group2 = "LogonHrs2"
$group3 = "LogonHrs3"
$groups = $group1,$group2,$group3

## Group 1 logon hours // 7:00 a.m. – 7:00 p.m. Monday – Friday, and 7:00 a.m. to 6:00 p.m. Saturday
[byte[]]$hours1 = @(0,0,0,0,224,255,1,224,255,1,224,255,1,224,255,1,224,255,1,224,255)

## Group 2 logon hours // 6:00 a.m. – 9:00 p.m. Monday – Sunday
[byte[]]$hours2 = @(7,240,255,7,240,255,7,240,255,7,240,255,7,240,255,7,240,255,7,240,255)

## Group 3 logon hours // 24 hours a day, 7 days per week
[byte[]]$hours3 = @(255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255)

<#
Each day of the week has 3 blocks. Each block is 8 hours.
Segment 1: 6pm-2am; Segment 2: 2am-10am; Segment 3: 10am-6pm
Note: I am in CST. These segements may be mapped to different timeframes if you are in a different time zone.
Each 1 hour block in the GUI represents 1 bit in a binary octet, but reversed order. Thus, a decimal value of 7 (binary value of 00000111) would equate to the first three hours of a segment. If the 7 were in segment 3 it would equate to 10am-1pm.

Example:

[byte[]]$hours = @(
	255,255,255, #Sun, 6pm previous day to 6pm present day
	255,255,255, #Mon
	255,255,255, #Tue
	255,255,255, #Wed
	255,255,255, #Thu
	255,255,255, #Fri
	255,255,255  #Sat
)
#>

# Iterate through group array
ForEach ($group in $groups) {

	# Retrieve a list of members for the current group
	#$membernames = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
	$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty samAccountName
	
	# Iterate through each member of the current group
	ForEach ($member in $members) {
		
		switch ($group) {
			$group1 {
				Get-ADUser -Identity $member |
				Set-ADUser -Replace @{logonhours = $hours1}
				Write-Host "Setting GROUP 1 logon times for $member, a member of group $group."
			}
			$group2 {
				Get-ADUser -Identity $member |
				Set-ADUser -Replace @{logonhours = $hours2}
				Write-Host "Setting GROUP 2 logon times for $member, a member of group $group."
			}
			$group3 {
				Get-ADUser -Identity $member |
				Set-ADUser -Replace @{logonhours = $hours3}
				Write-Host "Setting GROUP 3 logon times for $member, a member of group $group."
			}
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *