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

Darren Rose 496 Reputation points
2022-07-15T15:33:06.723+00:00

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  
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-07-15T19:54:00.75+00:00

    Try changing the first line to:

    $LastUsed = (Get-Date).AddDays(-365).ToString()  
    

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2022-07-15T19:20:36.75+00:00

    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?


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.