Question

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?

Was it helpful?

Solution

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

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

OTHER TIPS

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:

In WMI do: "select * from Win32_Session" there you'll have "StartTime" value.

Hope that helps.

Using WMI, the Win32Session is a great start. As well, it should be pointed out that if you're on a network you can use Win32_NetworkLoginProfile to get all sorts of info.

Set logins = objWMIService.ExecQuery _
   ("select * from Win32_NetworkLoginProfile")
For Each objSession in logins
   Wscript.Echo objSession.LastLogon
Next

Other bits of info you can collect include the user name, last logoff, as well as various profile related stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top