go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/uptime/windows.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package uptime 5 6 import ( 7 "encoding/json" 8 "io" 9 "time" 10 11 "go.mondoo.com/cnquery/providers/os/connection/shared" 12 "go.mondoo.com/cnquery/providers/os/resources/powershell" 13 ) 14 15 type WindowsUptime struct { 16 TotalMilliseconds float64 `json:"TotalMilliseconds"` 17 } 18 19 // ParseWindowsUptime parses the json output of gcim LastBootUpTime 20 // (Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime | ConvertTo-Json 21 func ParseWindowsUptime(uptime string) (time.Duration, error) { 22 var winUptime WindowsUptime 23 err := json.Unmarshal([]byte(uptime), &winUptime) 24 if err != nil { 25 return 0, err 26 } 27 28 milli := winUptime.TotalMilliseconds * float64(time.Millisecond) 29 return time.Duration(int64(milli)), nil 30 } 31 32 const WindowsUptimeCmd = "(Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime | ConvertTo-Json" 33 34 type Windows struct { 35 conn shared.Connection 36 } 37 38 func (s *Windows) Name() string { 39 return "Windows Uptime" 40 } 41 42 func (s *Windows) Duration() (time.Duration, error) { 43 cmd, err := s.conn.RunCommand(powershell.Wrap(WindowsUptimeCmd)) 44 if err != nil { 45 return 0, err 46 } 47 48 return s.parse(cmd.Stdout) 49 } 50 51 func (s *Windows) parse(r io.Reader) (time.Duration, error) { 52 content, err := io.ReadAll(r) 53 if err != nil { 54 return 0, err 55 } 56 return ParseWindowsUptime(string(content)) 57 }