@@ -33,12 +33,19 @@ import (
33
33
// getUptimeFunc returns the time for which the given service has been running.
34
34
func getUptimeFunc (service string ) func () (time.Duration , error ) {
35
35
return func () (time.Duration , error ) {
36
- // Using the WinEvent Log Objects to find the Service logs' time when the Service last entered running state.
36
+ // To attempt to calculate uptime more efficiently, we attempt to grab the process id to grab the start time.
37
+ // If the process id does not exist (meaning the service is not running for some reason), we will result to
38
+ // using the WinEvent Log Objects to find the Service logs' time when the Service last entered running state.
39
+ // In addition to filtering not by the logname=system we also filter on event id=7036 to reduce the number of
40
+ // entries the next command Where-Object will have to look through. id 7036 messages indicating a stopped or running service.
37
41
// The powershell command formats the TimeCreated of the event log in RFC1123Pattern.
38
42
// However, because the time library parser does not recognize the ',' in this RFC1123Pattern format,
39
43
// it is manually removed before parsing it using the UptimeTimeLayout.
40
- getTimeCreatedCmd := "(Get-WinEvent -Logname System | Where-Object {$_.Message -Match '.*(" + service +
41
- ").*(running).*'} | Select-Object -Property TimeCreated -First 1 | foreach {$_.TimeCreated.ToString('R')} | Out-String).Trim()"
44
+ getTimeCreatedCmd := `$ProcessId = (Get-WMIObject -Class Win32_Service -Filter "Name='` + service + `'" | Select-Object -ExpandProperty ProcessId);` +
45
+ `if ([string]::IsNullOrEmpty($ProcessId) -or $ProcessId -eq 0) { (Get-WinEvent -FilterHashtable @{logname='system';id=7036} ` +
46
+ `| Where-Object {$_.Message -match '.*(` + service + `).*(running).*'} | Select-Object -Property TimeCreated -First 1 | ` +
47
+ `foreach {$_.TimeCreated.ToString('R')} | Out-String).Trim() } else { (Get-Process -Id $ProcessId | Select starttime | ` +
48
+ `foreach {$_.starttime.ToString('R')} | Out-String).Trim() }`
42
49
out , err := powershell (getTimeCreatedCmd )
43
50
if err != nil {
44
51
return time .Duration (0 ), err
0 commit comments