Get-ADComputer -Filter on LastLogonDate - why does one method work and not the other?

Darren Rose 496 Reputation points


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  
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,282 questions
0 comments No comments
{count} votes

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 44,006 Reputation points

    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?