PowerShell & Active Directory- Accounts that are active but not logged in for ages
I have been really busy recently and my drafts are full of parts of scripts that I havent had time to make suitable for general comsumtion.
However here is a quicky but a goodie. This will check your AD for users that have not logged on for a set amount of days but still have active accounts. Its great for catching accounts that you probably should have deleted ages ago.
This is harder than it looks as last log in is not a value that is replicated accross domain controllers. That means you have to check all the AD servers in a domain to be sure you catch a users last login.
$Checkdays = 100 ## cut off date (in days) since last log in
$CutOffDate = date
$CutOffDate = $CutOffDate.AddDays(-$Checkdays)
function Get-ADUserLastLogon([string]$userName)
{
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Server $hostname -Properties lastLogon
if ($user.LastLogon -gt $time)
{
$time = $user.LastLogon
$Newestuser = $user
}
}
return $Newestuser
}
$ActiveADUsers = Get-ADUser -filter * -properties * |Where-Object enabled -EQ $true
foreach ( $ActiveADUser in $ActiveADUsers)
{
$lastlogondate = 0
$LatestLogon = Get-ADUserLastLogon -UserName $ActiveADUser
$lastlogondate =[datetime]::FromFileTime($LatestLogon.lastLogon)
if ($lastlogondate -lt $CutOffDate)
{
Echo $LatestLogon.Name
if ($lastlogondate -ne '01 January 1601 00:00:00')
{
Echo $lastlogondate
}
}
}