问题
We can use
Get-ADComputer $computerName -Properties LastLogonDate
to get LastLogonDate
. But how to know which user did the Last Logon? Get-ADUser
has a LastLogon
property, but it seems we could not use it to decide which computer the user logon.
回答1:
You're misunderstanding the meaning of LastLogonDate
in this context. It's the timestamp of when the computer account last authenticated against the domain, not the timestamp of when a user last logged into that particular computer.
To determine which user last logged into a specific computer you need to have logon event auditing enabled on that machine and extract the information from the Security eventlog (see here):
$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]}}
To limit the amount of data that is retrieved from the remote host I'd suggest to run Get-EventLog
with a starting date (-After
). Processing the entire Security eventlog could take a lot of time otherwise.
来源:https://stackoverflow.com/questions/25193662/get-lastlogonuser-and-lastlogondate-on-computers-in-ad