POSH-Script : Remove Inactive Active Directory Users

Over time, user and computer accounts become obsolete and needs elimination. This script will check user accounts in a specific Organizational Unit and remove the user account based on a date. This date must be set into the “extensionAttribute1” attribute but you can change this attribute by one another.

Below is the disabled user account:

adaccount

Based on this blog post, you can use the following script to remove disabled user account:

$Users = Get-ADUser -SearchBase "OU=_DisabledAccounts,DC=Demo,DC=local" -filter * -Properties UserPrincipalName,extensionAttribute1,DistinguishedName,Enabled | where {$_.enabled -eq $False}
$Today = (Get-Date).ToString('dd.MM.yyyy')
$UsersToDelete = $Users | ? {$_.extensionAttribute1 -eq $Today} 

$report = @()
foreach ($user in $UsersToDelete) {

    $o = New-Object PSCustomObject -Property @{
			Login = $user.UserPrincipalName;
			"Deleted date" = $user.extensionAttribute1;
                        "DistinguishedName" = $user.DistinguishedName;
    }	
	$report += $o
    Remove-AdUser -Identity $user.DistinguishedName -Confirm:$false
}

###
$css= "<style>"
$css= $css+ "BODY{ text-align: center; background-color:white;}"
$css= $css+ "TABLE{    font-family: 'Lucida Sans Unicode', 'Lucida Grande', Sans-Serif;font-size: 12px;margin: 10px;width: 100%;text-align: center;border-collapse: collapse;border-top: 7px solid #4A794E;border-bottom: 7px solid #4A794E;}"
$css= $css+ "TH{font-size: 13px;font-weight: normal;padding: 4px;background: #BDE3C1;border-right: 1px solid #234526;border-left: 1px solid #234526;color: #234526;}"
$css= $css+ "TD{padding: 4px;background: #BDE3C1; border-right: 1px solid #234526;border-left: 1px solid #234526;color: #669;hover:black;}"
$css= $css+  "TD:hover{ background-color:#234526;}"
$css= $css+ "</style>"
###

$body = "<center><h1>Deleted Users</h1></center><br><br>" 
$body += $report | Convertto-HTML -Head $css
send-mailmessage -to "to@domain.com" -from "from@domain.com" -subject "AD: Deleted users" -body ($body | out-string) -BodyAsHTML -SmtpServer "smtp.domain.com"

The script will send a report with the deleted user accounts.

adreport

Note: You can schedule the script to run daily.

Note2: You just need to change the “-SearchBase” parameter and add a date in the “extensionAttribute1” attribute.

 

 

Thanks for reading! You can follow me on Twitter @PrigentNico

About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.