Detect logging off and logging in powershell
Asked Answered
F

2

5

How can I detect if a user has logged on or off from a windows system (preferably that works with win7, vista or XP) using powershell?

I want to register the date and time of each logging on and off of the machine.

Thank you in advance

Funicle answered 2/3, 2011 at 19:6 Comment(1)
any final solution with full source code?Gadoid
P
8

You can get this infromation from the event log:

Get-EventLog System -Source Microsoft-Windows-Winlogon

Logons have an InstanceId of 7001, logoffs have 7002. The user account is a SID in ReplacementStrings.

Here is some more useful code for you.

$UserProperty = @{n="User";e={(New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}}
$TypeProperty = @{n="Action";e={if($_.EventID -eq 7001) {"Logon"} else {"Logoff"}}}
$TimeProeprty = @{n="Time";e={$_.TimeGenerated}}
Get-EventLog System -Source Microsoft-Windows-Winlogon | select $UserProperty,$TypeProperty,$TimeProeprty

You can also get these events from a remote computer by adding the "-ComputerName" parameter to Get-EventLog.

Pincenez answered 3/3, 2011 at 20:29 Comment(2)
It's exactly this! Thank you Jason.Funicle
Could you help me with this one: #5187193 Is there anything that can help understand better get-eventlog? Thank youFunicle
A
1

Such things are already be in the windows System log, with type "Winlogon". Don't know how you'd extract the information from there via powershell, but at least the logging part is already there for you.

Accelerate answered 2/3, 2011 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.