I’m looking to produce a powershell script that will return all users in the root and flag them if there account is inactive for more than 15 days and/or 30 days. I think i’m close but my If/Elseif statements dont seem to be working. Does anyone know a way to improve this?
$objSearcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$objSearcher.PropertiesToLoad.Add("displayName")
$objSearcher.PropertiesToLoad.Add("sAMAccountName")
$objSearcher.PropertiesToLoad.Add("lastLogonTimeStamp")
$userObjects = $objSearcher.FindAll()
foreach ($user in $userObjects)
{
$dn = $user.Properties.Item("displayName")
$sam = $user.Properties.Item("sAMAccountName")
$logon = $user.Properties.Item("lastLogonTimeStamp")
if($logon.Count -eq 0)
{
$lastLogon = "Never"
}
#Inactive for 15 days
elseif($logon.Value -ge (get-date).AddDays(-15))
{
$lastLogon = "Pending"
}
#Inactive for 30 days
elseif($logon.Value -ge (get-date).AddDays(-30))
{
$lastLogon = "Retired"
}
else
{
$lastLogon = [DateTime]$logon[0]
$lastLogon = $lastLogon.AddYears(1600)
}
"""$dn"",$sam,$lastLogon"
}
thanks
It appears that you are identifying anyone who has logged on from -15 days to now as “Pending” and from -30 days to -15 days as “Retired”.
Try flipping the order of your elseif’s, and changing the greater than or equal check to a less than or equal.
You also need to cast $logon[0] to a DateTime, like you are doing in your “else” block.
So, your code will become: