Filtering inactive computers in AD based on last logon timestamp/date

AdamHiatt-4835 20 Reputation points
2024-03-14T14:27:17.05+00:00

I am trying to create a PowerShell script that filters out inactive computer accounts in Active Directory, based on the last logon timestamp. I have tried different versions of the script, but keep getting an error that it can't parse anything related to "last logon".

Here is the script I am using:

# Specify the number of days to check for last logon
$daysInactive = 30
# Get the current date
$currentDate = Get-Date
# Calculate the inactive date
$inactiveDate = $currentDate.AddDays(-$daysInactive)
# Get inactive computer accounts
$inactiveComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $inactiveDate} -Properties LastLogonTimeStamp | 
    Select-Object Name, LastLogonTimeStamp
# Output the results
$inactiveComputers

I have tried replacing "LastLogonTimeStamp" with "LastLogonDate" and "lastLogon", but the error persists. However, I found another script that uses "LastLogonDate" and it works fine, so the "LastLogon" option seems to be valid.

$LastUsed = (Get-Date).AddDays(-365)
$ADcomputers = Get-ADComputer -Filter "OperatingSystem -notlike '*Server*' -and Name -notlike 'TEST*' -and LastLogonDate -gt '$LastUsed'" | select-object -Expand Name

This script seems to pull almost all machines which is unhelpful. I need help figuring out what I'm doing wrong.

Windows for business Windows Client for IT Pros Directory services Active Directory
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2024-03-14T14:58:44.35+00:00

    The LastLogonTimeStamp is stored in the AD as a 64-bit integer, not a DateTime object. You'd have to convert the integer to a DateTime object before you attempt the comparison to another DateTime object:

    [datetime]::FromFileTime(<LastLogonTimeStampValue>)


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.