通过 PowerShell 导出非活动用户的上次登录日期

问题描述 投票:0回答:1

我有一个命令可以导出已登录 12 个月的用户列表,但我很难导出上次登录日期和时间。

命令如下:

Search-ADAccount –AccountInActive -UsersOnly –TimeSpan 365:00:00:00 –ResultPageSize 2000 –ResultSetSize $null |?{$_.Enabled –eq $True} | Select-Object Name, SamAccountName, DistinguishedName, lastLogon| Export-CSV “C:\Users\Me\Desktop\InactiveUsers.CSV” –NoTypeInformation

但是 lastLogon 在 CSV 文件中显示空白。

我是 PowerShell 的新手,我知道命令可以变得更加流畅。

非常感谢任何帮助。

powershell automation active-directory
1个回答
2
投票

Search-ADAccount
没有从 AD 对象中提取默认属性以外的其他属性的选项,您可以使用
Get-ADUser
和精心设计的过滤器来查询过去一年未登录的用户。一种选择是查询用户的
lastLogonTimeStamp
属性
,但是这样做可能会冒得不到准确结果的风险,因为该属性不会实时复制。为了获得准确的信息,必须查询用户的
lastLogon
属性
,但是,由于该属性不会跨域复制,因此必须查询所有域控制器以获取用户的最新登录信息。

有关此主题的更多信息,请查看这篇优秀的 TechNet 文章:了解 AD 帐户属性 - LastLogon、LastLogonTimeStamp 和 LastLogonDate

$dateLimit = [datetime]::UtcNow.AddYears(-1).ToFileTimeUtc()

$AllDCs = Get-ADDomainController -Filter *
$logons = @{}

# use `!` for Enabled objects only: "(!userAccountControl:1.2.840.113556.1.4.803:=2)"
$params = @{
    LDAPFilter = -join @(
        "(&"                                                    # AND, all conditions must be met
            "(!samAccountName=krbtgt)"                          # exclude krbtgt from this query
            "(!samAccountName=Guest)"                           # exclude Guest from this query
            "(userAccountControl:1.2.840.113556.1.4.803:=2)"    # Disabled objects only
            "(lastLogon<=$dateLimit)"                           # lastLogon is below the limit
        ")"                                                     # close AND clause
    )
    Properties = 'lastLogon'
    # Add `SearchBase = "OUPath"` here if targeting a specific OU
}

foreach($DC in $AllDCs) {
    $params['Server'] = $DC

    foreach($user in Get-ADUser @params) {
        # this condition is always met on first loop iteration due to ldap filtering condition
        if($logons[$user.samAccountName].LastLogon -lt $user.LastLogon) {
            $logons[$user.samAccountName] = $user
        }
    }
}

$logons.Values | ForEach-Object {
    [PSCustomObject]@{
        Name              = $_.Name
        SamAccountName    = $_.SamAccountName
        DistinguishedName = $_.DistinguishedName
        lastLogon         = [datetime]::FromFileTimeUtc($_.lastLogon).ToString('u')
    }
} | Export-CSV "C:\Users\Me\Desktop\InactiveUsers.CSV" -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.