0

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
ak2595
  • 301
  • 1
  • 3
  • 16
  • 1
    Don't use `.ToString('yyyy-MM-dd')` on your expression if you want `Sort-Object` to sort `DateTime`. – Santiago Squarzon Feb 24 '22 at 14:37
  • What exactly is your problem? What strings are sorted incorrectly? Can you provide an example of wrongly sorted converted dates? – Vesper Feb 24 '22 at 14:41

1 Answers1

1

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 (@()).

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37