Published: 20.Jul 2021
Categories:

Disable inactive AD users with no logon activity in the last 90 days

Import-Module ActiveDirectory
 

$logPath = "<ENTER PATH HERE>\Logs\DisabledADMaccounts.txt"
$today = Get-Date -Format "dd.MM.yyyy"
$90days = (Get-Date).AddDays(-90)

 

# GET ADMIN USERS FROM OU
$ADMusers = Get-ADUser -SearchBase "<ENTER OU HERE>" -Properties * -Filter 'Enabled -eq $True' | `
            Select-Object SamAccountName,LastLogonDate | `
            Where-Object {$_.LastLogonDate -le $90days}
 

Write-Output "------- Current Date: $today --------" | Out-File -FilePath $logPath -Append
 

# DISABLE ADMIN USERS
foreach ($u in $ADMusers) 
{
    Disable-ADAccount -Identity $u.SamAccountName -Confirm:$false
    Set-ADUser -Identity $u.SamAccountName -Replace @{comment="Automatically disabled on $today because of no logon activity for more than 90 days."}
    Write-Output "User $($u.SamAccountName) was disabled on $today - no logon activity for more than 90 days" | Out-File -FilePath $logPath -Append
}

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
PowerAddict.net - Lubomir Goban  ---  Find me on - 
LinkedIn
0
Would love your thoughts, please comment.x
()
x