Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining how long the user is logged on to Windows

Tags:

windows

The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).

Any ideas?

like image 333
Hershi Avatar asked Jan 25 '23 04:01

Hershi


2 Answers

For people not familiar with WMI (like me), here are some links:

  • MSDN page on using WMI from various languages: http://msdn.microsoft.com/en-us/library/aa393964(VS.85).aspx
  • reference about Win32_Session: http://msdn.microsoft.com/en-us/library/aa394422(VS.85).aspx, but the objects in Win32_session are of type Win32_LogonSession (http://msdn.microsoft.com/en-us/library/aa394189(VS.85).aspx), which has more interesting properties.
  • WMI Explorer - a tool you can use to easily run queries like the one Michal posted.

And here's example querying Win32_Session from VBS:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & strComputer & "\root\cimv2")
Set sessions = objWMIService.ExecQuery _
   ("select * from Win32_Session")

For Each objSession in sessions
   Wscript.Echo objSession.StartTime
Next

It alerts 6 sessions for my personal computer, perhaps you can filter by LogonType to only list the real ("interactive") users. I couldn't see how you can select the session of the "current user".

[edit] and here's a result from Google to your problem: http://forum.sysinternals.com/forum_posts.asp?TID=3755

like image 135
Nickolay Avatar answered Jan 26 '23 18:01

Nickolay


In Powershell and WMI, the following one-line command will return a list of objects showing the user and the time they logged on.

Get-WmiObject win32_networkloginprofile | ? {$_.lastlogon -ne $null} | % {[PSCustomObject]@{User=$_.caption; LastLogon=[Management.ManagementDateTimeConverter]::ToDateTime($_.lastlogon)}}

Explanation:

  • Retrieve the list of logged in users from WMI
  • Filter out any non-interactive users (effectively removes NT AUTHORITY\SYSTEM)
  • Reformats the user and logon time for readability

References:

  • The WMI object to use: https://forum.sysinternals.com/topic3755.html
  • Formatting the date/time: https://blogs.msdn.microsoft.com/powershell/2009/08/12/get-systemuptime-and-working-with-the-wmi-date-format/
like image 41
Gnat Avatar answered Jan 26 '23 16:01

Gnat