Azure Automation - Disable Expired users in Active Directory

April 04, 2023

PowerShell script to search Active Directory for expired accounts, disable them and email results

OU to Search $OU = "OU=xxx,DC=Contoso,DC=com"

Email address to send results [string]$outmail = "servicedesk@contoso.com"

Import necessary PowerShell module Import-Module -Name ActiveDirectory

Set variables $date = Get-Date -Format "dd-mm-yy" $ExpiredAccounts = Search-ADAccount -SearchBase $OU -AccountExpired -UsersOnly -ResultSetSize $null | Select-Object AccountExpirationDate,Name,samAccountName,UserPrincipalName

Identify accounts that are expired and enabled, output to variable and disable foreach ($Account in $ExpiredAccounts){ if (Get-ADUser -Identity $Account.samAccountName | Where-Object -Property Enabled -eq True -OutVariable +Messagebodycontent){ Disable-ADAccount -Identity $Account.samAccountName } }

Create body of email $MessageBody = $MessageBodyContent.UserPrincipalName | Out-String

Email list of disabled users Send-MailMessage -From "Contoso Expired Accounts contosodisable@contoso.com" -To $Outmail -SmtpServer "smtp.contoso.com" -Subject "Contoso Expired Accounts Disabled $Date" -Body $MessageBody -BodyAsHtml


Profile picture

Written by James Haywood Infrastructure Architect - mostly working in the EUC and Azure domains.