Powershell – Advanced Selective Force Password Change AD

 

This script forces users to change their password if they haven’t changed it in the last 5 days. I also filtered this by site (OU) in AD.

#create all necessary variables
$currenttime = get-date
$lasttime = $currenttime.AddDays(-5)
$changedusers = @()
$allsites = @()

 

#choose users from specific sites and add them to the array
$site1 = Get-ADUser -Filter * -SearchBase “OU=myou,DC=mydomain,DC=local” -Properties passwordlastset
$allsites += $site1
$site2 = Get-ADUser -Filter * -SearchBase “OU=myou,DC=mydomain,DC=local” -Properties passwordlastset
$allsites += $site2
$site3 = Get-ADUser -Filter * -SearchBase “OU=myou,DC=mydomain,DC=local” -Properties passwordlastset
$allsites += $site3
$site4 = Get-ADUser -Filter * -SearchBase “OU=myou,DC=mydomain,DC=local” -Properties passwordlastset
$allsites += $site4

 

#nested for loop to go through each site then each user in each site

foreach ($site in $allsites) {

foreach ($user in $site) {
#if user pass last reset is greater than 5 days ago or it’s empty, reset it, add it to an array for later
if ($user.PasswordLastSet -le $lasttime -or $user.PasswordLastSet -eq $null)

{
$user | set-aduser -ChangePasswordAtLogon:$True
$changedusers += $user.Name
}
}
}

#export results
$changedusers | out-file C:\changedusers.txt

Leave a comment