Accounts which have not yet signed in will have a null `lastLogon` We do want to disable accounts which have never logged in, but want to allow IT to create accounts before the user starts. The added `$MinAccountAge` is the minimum age of the account based on the lastCreated attribute before the script will include them to disable.
		
			
				
	
	
		
			43 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			PowerShell
		
	
	
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			PowerShell
		
	
	
	
	
	
# 
 | 
						|
# Disable-InactiveAdUser
 | 
						|
# 
 | 
						|
 | 
						|
$UsersOU = "OU=Users,OU=Default-First-Site-Name,DC=CONTOSO,DC=COM"
 | 
						|
$MaxAccountAge = 45
 | 
						|
# Allow a grace period for newly created accounts which have not yet logged in
 | 
						|
$MinAccountAge = 7
 | 
						|
 | 
						|
$SmtpServer = 'contoso-com.mail.protection.outlook.com'
 | 
						|
$SmtpPort = 25
 | 
						|
$SmtpFrom = 'Contoso SOC <security@contoso.com>'
 | 
						|
$SmtpTo = @(
 | 
						|
    'security@contoso.com'
 | 
						|
)
 | 
						|
$SmtpSubject = "Contoso, Inc.: Disabled inactive AD accounts over $MaxAccountAge days"
 | 
						|
 | 
						|
# Get a list of enabled AD users who have not logged in in $MaxAccountAge days
 | 
						|
$Users = Get-ADUser -SearchBase "$UsersOU" -Filter * -Properties * `
 | 
						|
   | where { $_.Enabled -eq $true -and [DateTime]::FromFileTime($_.lastLogon) -lt (Get-Date).AddDays(-$MaxAccountAge) -and $_.whenCreated -lt (Get-Date).AddDays(-$MinAccountAge) } `
 | 
						|
   | select DisplayName,userPrincipalName,lastLogon,distinguishedName | % { $_.lastLogon = [DateTime]::FromFileTime($_.lastLogon); $_ }
 | 
						|
 | 
						|
# Disable the accounts
 | 
						|
foreach ($User in $Users) {
 | 
						|
    Disable-ADAccount -Identity $User.distinguishedName
 | 
						|
}
 | 
						|
 | 
						|
# Email a report
 | 
						|
if (($Users.distinguishedName).Count -gt 0) {
 | 
						|
    $EmailBody = @"
 | 
						|
<h2>Users Disabled</h2><br/>
 | 
						|
<p>The following user accounts have been disabled:</p>
 | 
						|
<ul>
 | 
						|
    $($Users | % { "<li>$($_.DisplayName) <$($_.userPrincipalName)>, not logged in since $($_.lastLogon)</li>" })
 | 
						|
</ul><br/>
 | 
						|
<p>This email was sent automatically. Please do not reply.</p><br/>
 | 
						|
<p><pre>$($UsersOU) $(Get-Date)</pre></p>
 | 
						|
"@
 | 
						|
 | 
						|
    Send-MailMessage -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -From $SmtpFrom -To $SmtpTo `
 | 
						|
        -Subject $SmtpSubject -Body "$EmailBody" -BodyAsHtml
 | 
						|
}
 |