52 lines
1.7 KiB
PowerShell
52 lines
1.7 KiB
PowerShell
#
|
|
# Disable-InactiveAdUser
|
|
#
|
|
|
|
$SmtpServer = 'qlmi-com.mail.protection.outlook.com'
|
|
$SmtpPort = 25
|
|
$SmtpFrom = 'Quantum Leap Security <security@qlmi.com>'
|
|
$SmtpTo = @(
|
|
'security@qlmi.com'
|
|
)
|
|
|
|
$MaxAccountAge = 45
|
|
$UsersOU = "OU=Users - Synced,OU=_Quantum Leap,DC=QLCOM,DC=COM"
|
|
|
|
# Get a list of enabled AD users who have not logged in in $MaxAccountAge days
|
|
$Users = Get-ADUser -Filter 'enabled -eq $true' -SearchBase "$UsersOU" | % {
|
|
New-Object PSObject -Property @{
|
|
"userPrincipalName" = $_.userPrincipalName
|
|
"Enabled" = $_.Enabled
|
|
"lastLogon" = [DateTime]::FromFileTime(($_ | Get-ADObject -Properties lastLogon).LastLogon)
|
|
"distinguishedName" = $_.distinguishedName
|
|
}
|
|
} | Where-Object -FilterScript { $_.lastLogon -lt (Get-Date).AddDays(-$MaxAccountAge) }
|
|
|
|
# Export a report of the users
|
|
if (!(Test-Path -Path 'C:\temp')) {
|
|
New-Item -Path 'C:\temp' -ItemType Directory -ErrorAction SilentlyContinue
|
|
}
|
|
$ReportPath = Join-Path -Path 'C:\temp' -ChildPath "disabled_users_$(Get-Date -UFormat '%s').csv"
|
|
$Users | Export-Csv -NoTypeInformation -Path $ReportPath
|
|
|
|
# Disable the accounts
|
|
foreach ($User in $Users) {
|
|
Disable-ADAccount -Identity $User.distinguishedName
|
|
}
|
|
|
|
# Email the report
|
|
if (($Users.Enabled).Count -gt 0) {
|
|
$EmailBody = @"
|
|
<h2>Users Disabled</h2><br/>
|
|
<p>The following user accounts have been disabled:</p>
|
|
<ul>
|
|
$($Users | % { "<li>$($_.userPrincipalName), not logged in since $($_.lastLogon)</li>" })
|
|
</ul><br/>
|
|
<p>This email was sent automatically. Please do not reply.</p>
|
|
"@
|
|
|
|
Send-MailMessage -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -From $SmtpFrom -To $SmtpTo `
|
|
-Subject "Disabled inactive AD accounts over max age $MaxAccountAge days" `
|
|
-Body "$EmailBody" -BodyAsHtml
|
|
}
|