Try changing the first line to:
$LastUsed = (Get-Date).AddDays(-365).ToString()
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi
Running PowerShell to get list of users which meet criteria from AD, can someone explain to me why the first query with hard coded date works fine and returns results:-
$ADcomputers2 = Get-ADComputer -Filter "OperatingSystem -notlike '*Server*' -and Name -notlike 'TEST*' -and LastLogonDate -gt '15 July 2021 16:22:17'" | select-object -Expand Name
But this second one using a variable for date returns no results even though value of $LastUsed is exactly the same format / value as I used in the above test?
$LastUsed = (Get-Date).AddDays(-365)
$ADcomputers = Get-ADComputer -Filter "OperatingSystem -notlike '*Server*' -and Name -notlike 'TEST*' -and LastLogonDate -gt '$LastUsed'" | select-object -Expand Name
Try changing the first line to:
$LastUsed = (Get-Date).AddDays(-365).ToString()
When $lastUsed is used in the way you're using it, the object's "ToString()" method will return " AM" or " PM" at the end of the returned value.
If you change your filter to " . . . -and LastLogonDate -gt '15 July 2021 4:22:17 PM'" does it still work?