Scenario: All terminated employee accounts are disabled and moved to an OU where they are retained for 90 days before finally being deleted. I want that accounts which complete 90 days of retention are automatically deleted on a specific date of every month. I am taking WhenChanged AD attribute to decide the retention instead of LastLogonTimeStamp. You are free to choose any of the two.
I decided that this task be automated in two steps where admin gets an email, a few days in advance, containing all the accounts which are about to get deleted
User cleanup – Send notification
## Defining All Variables.
$date = Get-Date
$databasepath = "C:\Scripts\User_Cleanup_Task\Data"
$log = "$databasepath\Logs\Logfile.log"
## Fetching all disabled users.
$searchBases = "OU=DisabledContractors,OU=Employees_Disabled,DC=abc,DC=net", "OU=DisabledEmployees,OU=Employees_Disabled,DC=abc,DC=net"
If (Test-Path "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" , "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv") {
Remove-Item "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" , "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv"
}
foreach ($searchBase in $searchBases) {
$inactiveDays = "90"
$userinfo = Get-ADuser -SearchBase $searchBase -Filter *
foreach ($user in $userinfo.Name) {
$whenChanged = Get-ADUser -Identity $user -Properties * | Select-Object -ExpandProperty lastLogonTimestamp
$shouldBeDate = $date.AddDays( - $inactiveDays)
if ($whenChanged -le $shouldBeDate) {
Add-Content -Value $user -Path "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv"
}
}
}
## Adding header (name) so that detailed data can be extracted.
Import-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv" -header "name" | export-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" -NoTypeInformation
## Extracting detailed report of user accounts to be deleted which will be emailed.
Import-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" | ForEach-Object {Get-ADUser $_.name -properties * | Select-Object DisplayName,GivenName,CanonicalName,objectSid,ObjectClass,mail,Title,Manager,UserPrincipalName,AccountExpirationDate,Office,City,PostalCode,Country,StreetAddress,createTimeStamp,Department,Description,DistinguishedName,EmailAddress,PasswordExpired,PasswordNeverExpires,Enabled,HomePhone,lastLogonTimestamp,mobile,MobilePhone,Modified,msExchMailboxTemplateLink,msExchUsageLocation,msExchWhenMailboxCreated,msRTCSIP-PrimaryUserAddress,whenChanged,whenCreated } | export-csv "C:\Scripts\User_Cleanup_Task\Data\CSVs\InactiveUserAccountDetails.csv" -NoTypeInformation
## Send Mail
Send-MailMessage -From "UserCleanup@abc.com" -To "abc1@yahoo.com" , "abc2@yahoo.com" -Subject "User Accounts to be deleted." -Body "Attached CSV contain all disabled stale users accounts which have completed 90 days of retention and are ready for deletion." -Attachments "C:\Scripts\User_Cleanup_Task\Data\CSVs\InactiveUserAccountDetails.csv"
## Maintaining log
$inactiveUserCount = (Get-Content "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv").Count
Add-Content -Value "$date : Email for total $inactiveUserCount inactive User accounts which are ready for deletion have been sent." -Path $log
User cleanup -Deletion
## Defining All Variables.
$date = Get-Date
$databasepath = "C:\Scripts\User_Cleanup_Task\Data"
$log = "$databasepath\Logs\Logfile.log"
## Fetching all disabled users.
$searchBases = "OU=DisabledContractors,OU=Employees_Disabled,DC=abc,DC=net", "OU=DisabledEmployees,OU=Employees_Disabled,DC=abc,DC=net"
If (Test-Path "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" , "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv") {
Remove-Item "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" , "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv"
}
foreach ($searchBase in $searchBases) {
$inactiveDays = "90"
$userinfo = Get-ADuser -SearchBase $searchBase -Filter *
foreach ($user in $userinfo.Name) {
$whenChanged = Get-ADUser -Identity $user -Properties * | Select-Object -ExpandProperty lastLogonTimestamp
$shouldBeDate = $date.AddDays( - $inactiveDays)
if ($whenChanged -le $shouldBeDate) {
Add-Content -Value $user -Path "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv"
}
}
}
$inactiveUserCount = (Get-Content "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv").Count
Add-Content -Value "$date : Total $inactiveUserCount disabled user accounts have been deleted. List can be found at C:\Scripts\User_Cleanup_Task\Data\Archives" -Path $log
##Adding header (name) so that detailed data can be extracted.
Import-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv" -header "name" | export-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" -NoTypeInformation
##Extracting detailed report of user accounts to be deleted which will be emailed.
Import-csv "C:\Scripts\User_Cleanup_Task\Data\InactiveUsers.csv" | ForEach-Object {Get-ADUser $_.name -properties * | Select-Object DisplayName,GivenName,CanonicalName,objectSid,ObjectClass,mail,Title,Manager,UserPrincipalName,AccountExpirationDate,Office,City,PostalCode,Country,StreetAddress,createTimeStamp,Department,Description,DistinguishedName,EmailAddress,PasswordExpired,PasswordNeverExpires,Enabled,extensionAttribute1,extensionAttribute2,extensionAttribute3,extensionAttribute4,extensionAttribute5,extensionAttribute6,extensionAttribute7,extensionAttribute8,extensionAttribute9,extensionAttribute10,extensionAttribute15,HomePhone,lastLogonTimestamp,mobile,MobilePhone,Modified,msExchLitigationHoldDate,msExchLitigationHoldOwner,msExchMailboxTemplateLink,msExchUsageLocation,msExchWhenMailboxCreated,msRTCSIP-PrimaryUserAddress,whenChanged,whenCreated } | export-csv "C:\Scripts\User_Cleanup_Task\Data\CSVs\InactiveUserAccountDetails.csv" -NoTypeInformation
## Starting Delete Inactive Users.
$Users = Get-Content -Path "C:\Scripts\User_Cleanup_Task\Data\InactiveUser.csv"
foreach ($User in $Users) {
Get-ADUser -Identity $User | Remove-ADObject -Recursive -Confirm:$false
Add-Content -Value "$date : $User account has been deleted from Active Directory." -Path $log
}
##Renaming file
Move-Item "C:\Scripts\User_Cleanup_Task\Data\CSVs\InactiveUserAccountDetails.csv" -Destination "C:\Scripts\User_Cleanup_Task\Data\CSVs\DeletedUserAccountDetails.csv" -Force
Start-Sleep -s 5
##Send Mail
Send-MailMessage -From "UserCleanup@abc.com" -To "abc1@yahoo.com" , "abc2@yahoo.com" -Subject "User Cleanup task completed successfully" -Body "Attached CSV contain all terminated user acocunts which completed 90 days of retention. These accounts have been deleted." -Attachments "C:\Scripts\User_Cleanup_Task\Data\CSVs\DeletedUserAccountDetails.csv"
Start-Sleep -s 15
##Moving detailed sheet to Archive folder
Move-Item "C:\Scripts\User_Cleanup_Task\Data\CSVs\DeletedUserAccountDetails.csv" -Destination "C:\Scripts\User_Cleanup_Task\Data\Archives\DeletedUserAccountDetails$(get-date -f yyyy-MM-dd-hh).csv"
These scripts can be set to run as a scheduled task. If anyone of you would like me to explain the scripts line by line, please let me know through comments.