Powershell - Getting Last Log Off Date and Time of

2019-07-24 11:38发布

I'm not very good with powershell so here goes.

I'm having trouble with displaying the last logoff Date and time of a computer. So far I have:

$Logoff = GWMI -Comp $strComputer -Cl Win32_NetworkLoginProfile | 
    foreach-object {Write-Host "Last Logoff: "$_.Lastlogoff}

This gives me a list of I guess logoff dates and time. This seemed ok so I tried to convert the output using ConvertToDateTime to get a readable date/time but I don't now how to get it to work when a selection of datetimes are sent back. I've tried:

$Logoff = GWMI -Comp $strComputer -Cl Win32_NetworkLoginProfile | 
    foreach-object {Write-Host "Last Logoff: "ConvertToDateTime($_)}

but as you can guess this didn't work. Can someone point me in the right direction? Maybe I'm going about this wrong and I should be looking at a different way of getting last logoff/logoff details

2条回答
家丑人穷心不美
2楼-- · 2019-07-24 12:01

Another way of achieving the same result as Ansgar's suggested command:

Get-EventLog -ComputerName $Computer -LogName 'Security' -InstanceId 4634 -newest 1 | Select-object TimeGenerated

On my computer, there was a big difference in time taken to retrieve the result.

查看更多
【Aperson】
3楼-- · 2019-07-24 12:04

You could read the most recent logoff event from the computers' eventlogs:

Get-EventLog -Computer $strComputer "Security" `
  | ? { $_.EventId -eq 4634 } `
  | sort -Desc TimeGenerated `
  | select -First 1 TimeGenerated

Note that reading the Security eventlog requires admin privileges. Also, reading the entire eventlog may require significant amounts of time, so you may want to restrict the processed events by date (-After (Get-Date).AddDays(-1)) or by number (-Newest 500).

查看更多
登录 后发表回答