Home > Blockchain >  Get-ADUser unable to sort by LastLogonDate
Get-ADUser unable to sort by LastLogonDate

Time:11-24

I'm trying to sort my disabled users by the last date they logged in.

I used the following command:

Get-ADUser -Filter "samaccountname -eq '$user' -and enabled -eq '$False'" -Properties * | 
select samaccountname, displayname, emailaddress, LastLogonDate |
Sort-Object -Property LastLogonDate

I'm not sure why, but it doesn't sort the LastLogonDate property. I keep getting an unsorted list of my disabled users.

CodePudding user response:

Continuing from my comment, I think the code you show is the part inside a loop where you iterate users, perhaps based on the input from a CSV file.

Your code only finds one single user and sorts that one object on its LastLogonDate.

The sorting should be done after you have collected all your users like

# capture the resulting objects from a collection of users
$result = foreach ($user in $MyListOfUserSamAccountNames) {
    Get-ADUser -Filter "samaccountname -eq '$user' -and enabled -eq '$False'" -Properties displayname, emailaddress, LastLogonDate | 
    Select-Object samaccountname, displayname, emailaddress, LastLogonDate
}
# here is where you sort the result for output
$result | Sort-Object -Property LastLogonDate

Please bear in mind that the calculated property LastLogonDate (not really a AD attribute at all) is not replicated within the domain and to get the most accurate value, you need to iterate the domaincontrollers in your domain.

  • Related