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.