9/02/2008

Get User's last successful and failed logon

The following VBScript will show the last successful and the last failed logon of the current user. Depending of the OS Version the event id's from eventvwr has to be customized.

  1. Dim objNetwork : Set objNetwork = CreateObject("WScript.Network")  
  2. strComputer = "."  
  3. Dim EventTime, strUsername  
  4. strLogonSuccess = "528"  
  5. strLogonError = "529"  
  6. Set objWMIService = GetObject("winmgmts:" & "{(Security)}!\\" & strComputer & "\root\cimv2")  
  7.    
  8. 'Determine the last successful logon process  
  9. Set colLoggedEvents = objWMIService.ExecQuery ("Select * from Win32_NTLogEvent Where Logfile = 'Security' and EventCode = '" &strLogonSuccess &"'")  
  10. For Each objEvent in colLoggedEvents  
  11.  If Not IsNull(objEvent.User) And objEvent.User = objNetwork.UserDomain &"\" &objNetwork.UserName Then  
  12.   If cint(objEvent.Eventcode) = cint(strLogonSuccess) Then  
  13.    Call ConvertTime(objEvent.TimeWritten)  
  14.    Wscript.Echo "The last successful Logon from " &objEvent.User &" was at " &EventTime  
  15.    Exit For  
  16.   End If  
  17.  End If  
  18. Next  
  19.    
  20. 'Determine the last failed logon process  
  21. Set colLoggedEvents = objWMIService.ExecQuery ("Select * from Win32_NTLogEvent Where Logfile = 'Security' and EventCode = '" &strLogonError &"'")  
  22. For Each objEvent in colLoggedEvents  
  23.  'Convert username out of the eventvwr message  
  24.  Call GetUsername(objEvent.Message)  
  25.    
  26.  'Check if username from event matches local logged in user  
  27.  If lcase(cstr(strUsername)) = lcase(cstr(objNetwork.UserName)) Then  
  28.   If cint(objEvent.Eventcode) = cint(strLogonError) Then  
  29.    Call ConvertTime(objEvent.TimeWritten)  
  30.    Wscript.Echo "The last failed Logon from " &strUsername &" was at " &EventTime  
  31.    Exit For  
  32.   End If  
  33.  End If  
  34. Next  
  35.    
  36. Function ConvertTime(datetime)  
  37. EventTime = Mid(datetime, 5, 2) & "/" & Mid(datetime, 7, 2) & "/" & _  
  38.     Mid(datetime, 1, 4) & " " & Mid(datetime, 9, 2) & ":" & _  
  39.     Mid(datetime, 11, 2) & "." & Mid(datetime, 13, 2)  
  40. End Function  
  41.    
  42. Function GetUsername(strMessage)  
  43.  strStart = InStr(strMessage,"User Name:") + 10  
  44.  strEnd = InStr(strMessage,"Domain:")  
  45.  strLen = strEnd - strStart  
  46.    
  47.  strUsername = Replace(Replace(Replace(Replace(Mid(strMessage,strStart,strLen)," ",""),vbTab, ""),VbCrLf,""), vbNewLine,"")  
  48. End Function  

No comments: