You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell导出非活跃用户上次登录日期问题求助

解决AD未登录用户导出中lastLogon为空的问题

你遇到的lastLogon字段为空,主要有两个核心原因:

  • Search-ADAccount 默认不会加载lastLogon属性,需要显式指定或改用同步属性
  • lastLogon是域控制器本地属性,仅记录用户登录到该DC的时间,不会跨DC同步,直接获取大概率为空或不准确

对于查找12个月未登录的用户,推荐使用lastLogonTimestamp——这个属性会在域内同步(默认9-14天同步一次),完全满足长期 inactive 用户的查询需求。

修改后的优化命令

Search-ADAccount -AccountInactive -UsersOnly -TimeSpan 365.00:00:00 -ResultPageSize 2000 -ResultSetSize $null -Enabled $true | 
    Select-Object Name, SamAccountName, DistinguishedName, 
        @{Name='LastLogonTimestamp'; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} |
    Export-CSV "C:\Users\Me\Desktop\InactiveUsers.CSV" -NoTypeInformation

关键优化点说明

  • 把-Enabled $true直接加入Search-ADAccount参数,避免管道后二次过滤,提升查询效率
  • 通过计算属性将AD存储的lastLogonTimestamp(FileTime格式)转换为可读的日期时间

如果确实需要精准的用户最后一次登录到任意DC的时间,可使用以下遍历所有域控制器的命令(速度较慢,适合小规模域):

$domain = Get-ADDomain
$allDCs = $domain.ReplicaDirectoryServers
$inactiveUsers = Search-ADAccount -AccountInactive -UsersOnly -TimeSpan 365.00:00:00 -ResultPageSize 2000 -ResultSetSize $null -Enabled $true

$results = foreach ($user in $inactiveUsers) {
    $latestLogon = [DateTime]::MinValue
    foreach ($dc in $allDCs) {
        $userObj = Get-ADUser $user.SamAccountName -Server $dc -Properties lastLogon
        if ($userObj.lastLogon -and [DateTime]::FromFileTime($userObj.lastLogon) -gt $latestLogon) {
            $latestLogon = [DateTime]::FromFileTime($userObj.lastLogon)
        }
    }
    [PSCustomObject]@{
        Name = $user.Name
        SamAccountName = $user.SamAccountName
        DistinguishedName = $user.DistinguishedName
        LastLogon = $latestLogon
    }
}

$results | Export-CSV "C:\Users\Me\Desktop\InactiveUsers_WithExactLastLogon.CSV" -NoTypeInformation

内容的提问来源于stack exchange,提问作者S.Mahmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:15:25