Category Archives: Active Directory

Modify Multiple Active Directory Accounts – PowerShell

The other day I wrote a script that populated my test server with 290 accounts. You can check it out HERE. Today I decided I would modify the logon hours for those accounts… It turned out to be more difficult than I thought because of the way you have to present the logon hours:

[byte[]]$hours = @(0,0,0,0,224,255,3,224,255,3,224,255,3,224,255,3,224,255,3,0,0)

There were a couple of sites that tried to explain it, but it easier to set the logon hours through the Active Directory Users and Computers MMC Snapin on a test user. Then go into ADSI Edit and take a look at the properties on the object and change the “Value Format” to Decimal:

ADSIEdit1

After running the script, the end result is 290 accounts in the Employees OU changed from the default 24/7 logon to the following:

ModHours

#Check if we are running in elevated powershell
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "You do not have Administrator rights to run this script!`nPlease re-run this script as an Administrator!"
    Break
}

#Check if the Active Directory Module is loaded
if(-not (Get-Module ActiveDirectory)){
	Import-Module ActiveDirectory
}

#Grab the specific accounts we want(Everything in the Employees OU)
$employees = Get-ADUser -Filter * -SearchBase "OU=Employees,DC=lmnop,DC=local"

#Logon Hours Monday - Friday from 5AM - 6PM
#(I don't know how this works so I set it in MMC and check the value in ADSIEdit in Decimal)

[byte[]]$hours = @(0,0,0,0,224,255,3,224,255,3,224,255,3,224,255,3,224,255,3,0,0)

# create a hashtable to update the logon hours and a description
$replaceHashTable = New-Object HashTable
$replaceHashTable.Add("logonHours", $hours)
$replaceHashTable.Add("description", "Employees can only logon from Monday through Friday from 5:00 AM to 6:00 PM")

$count = 0

foreach($employee in $employees){
Write-Host "Changing logon hours for" $employee.SamAccountName
Set-ADUser $employee.SamAccountName -Replace $replaceHashTable
$count++
}

Write-Host $count " Accounts have been modified"