# encoding: ascii
# api: powershell
# title: Delete AD Users
# description: This script will delete all Active Directory User accounts that have not logged in within the number of days specified in the $NumDays variable. The script only deletes the Active Directory user accounts, not any associated Exchange mailboxes. The script also includes the Delete-ADUser function, which can be used separately from this script. All accounts that are deleted are logged in the “Removed-User-Accounts.log” file found in the local directory. The format of the log file is very basic, but effective.
# version: 0.1
# type: function
# author: AlphaSun
# license: CC0
# function: Delete-ADUser
# x-poshcode-id: 5992
# x-archived: 2015-09-10T17:18:45
# x-published: 2015-08-26T18:20:00
#
#
function Delete-ADUser
{
Param($userName = $(throw 'Enter a username to delete'))
$searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"","(&(objectcategory=user)(sAMAccountName=$userName))")
$user = $searcher.findone().GetDirectoryEntry()
$user.psbase.DeleteTree()
}
$NumDays = 90
$LogDir = ".\Removed-User-Accounts.log"
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findone()
Write-Output `n`n"----------------------------------------" "ACCOUNTS OLDER THAN "$NumDays" DAYS" "PROCESSED ON:" $currentDate "----------------------------------------" `
| Out-File $LogDir -append
if ($users.Count -eq 0)
{
Write-Output " No account needs to be removed." | Out-File $LogDir -append
}
else
{
foreach ($user in $users)
{
# Read the user properties
[string]$adsPath = $user.Properties.adspath
[string]$displayName = $user.Properties.displayname
[string]$samAccountName = $user.Properties.samaccountname
[string]$lastLogonInterval = $user.Properties.lastlogontimestamp
# Delete the user
Delete-ADUser $samAccountName
# Convert the date and time to the local time zone
$lastLogon = [System.DateTime]::FromFileTime($lastLogonInterval)
Write-Output " Removed user " $displayName" | Username: "$samAccountName" | Last Logon: "$lastLogon"`n" `
| Out-File $LogDir -append
}
}