Powershell 在AD中的计算机上获取LastLogonUser和LastLogonData

Powershell 在AD中的计算机上获取LastLogonUser和LastLogonData,powershell,active-directory,ldap,Powershell,Active Directory,Ldap,我们可以使用 Get-ADComputer $computerName -Properties LastLogonDate 获取lastLogonData。但如何知道上次登录的用户是谁Get ADUser有一个LastLogon属性,但我们似乎无法使用它来决定用户登录的计算机。在这种情况下,您误解了LastLogonData的含义。它是计算机帐户上次针对域进行身份验证的时间戳,而不是用户上次登录该特定计算机的时间戳 要确定上次登录到特定计算机的用户,您需要在该计算机上启用登录事件审核,并从安全

我们可以使用

Get-ADComputer $computerName -Properties LastLogonDate

获取
lastLogonData
。但如何知道上次登录的用户是谁
Get ADUser
有一个
LastLogon
属性,但我们似乎无法使用它来决定用户登录的计算机。

在这种情况下,您误解了
LastLogonData
的含义。它是计算机帐户上次针对域进行身份验证的时间戳,而不是用户上次登录该特定计算机的时间戳

要确定上次登录到特定计算机的用户,您需要在该计算机上启用登录事件审核,并从安全事件日志中提取信息(请参阅):

为了限制从远程主机检索的数据量,我建议运行带有开始日期(
-After
)的
Get EventLog
)。否则,处理整个安全事件日志可能需要很多时间

$computer = '...'

Get-EventLog Security -Computer $computer -InstanceId 4624 -EntryType SuccessAudit |
    Where-Object {
        $_.Message -match 'logon type:\s+(2|10)\s' -and
        $_.Message -match 'new logon:[\s\S]*?account name:\s+(.*?)\s'
    } |
    Sort-Object TimeGenerated -Desc |
    Select-Object -First 1 TimeGenerated, @{n='Account';e={$matches[1]}}