Home > other >  How to sort-object lastlogon -descending?
How to sort-object lastlogon -descending?

Time:02-24

I have to check the lastlogon for different users.

My script queries my domain controllers to output my report, however I have an issue.

My report does not come out in descending order. I added sort-object lastlogon -descending, but the dates don't come out correctly in my file. Can you help me?

$data = @()
$DCs = Get-ADDomainController -Filter * | Select-Object -ExpandProperty name
$users = 
@'
samaccountname;
user1
user2
'@ | ConvertFrom-Csv -Delimiter ';'
foreach ($DC in $DCs) {
            foreach($user in $users)
                {$data  = Get-ADUser $User.samaccountname.Trim() -Properties displayname, userprincipalname, samaccountname, lastlogon -server $DC | Select-Object DisplayName, UserPrincipalName, SamAccountName, Enabled, @{name='LastLogon';expression={[datetime]::fromFileTime($_.lastLogon).ToString('yyyy-MM-dd')}} }
                    }
$data | Group-Object Lastlogon | Foreach-Object {$_.Group | Sort-Object lastLogon -Descending | Select-Object  -Last 10 | Export-Excel "C:\temp\lastlogon ($(Get-Date -Format "yyyy-MM-dd")).xlsx"}

write-host Done! -ForegroundColor Green

CodePudding user response:

It's unclear what you want to accomplish with your script but basically, if you .ToString(..) a DateTime object then Sort-Object will not know how to sort it correctly. Here is how you can approach your code:

$DCs = (Get-ADDomainController -Filter *).Name
$users = @'
samaccountname;
user1
user2
'@ | ConvertFrom-Csv -Delimiter ';'

& {
    foreach ($DC in $DCs) {
        foreach($user in $users) {
            $params = @{
                Properties = 'displayname', 'lastlogon'
                Server     = $DC
                Identity   = $User.samaccountname.Trim()
            }
            Get-ADUser @params | Select-Object @(
                'DisplayName'
                'UserPrincipalName'
                'SamAccountName'
                'Enabled'
                @{
                    Name = 'LastLogon'
                    Expression = {
                        [datetime]::fromFileTime($_.LastLogon)
                    }
                }
            )
        }
    }
} | Group-Object { $_.Lastlogon.ToString('yyyy-MM-dd') } | Foreach-Object {
    $_.Group | Sort-Object LastLogon -Descending | Select-Object -Last 10 |
    Export-Excel "C:\temp\lastlogon ($(Get-Date -Format "yyyy-MM-dd")).xlsx"
}

You also want to avoid adding elements ( =) to a fixed collection (@()).

  • Related