如何排序对象 lastlogon -descending?

How to sort-object lastlogon -descending?

我必须检查不同用户的上次登录。

我的脚本查询我的域控制器以输出我的报告,但是我遇到了问题。

我的报告没有按降序排列。我添加了 sort-object lastlogon -descending,但我的文件中的日期显示不正确。你能帮帮我吗?

$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

目前还不清楚您要用脚本完成什么,但基本上,如果您 .ToString(..) 一个 DateTime 对象,那么 Sort-Object 将不知道如何正确排序它。以下是处理代码的方法:

$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"
}

你也想.