要使用PowerShell使Windows系统正常运行,我们可以使用类名称为Win32_OperatingSystem的CIM Instance方法。使用上述类后,将有一个名为LastBootupTime的属性,该属性显示上次重新启动计算机的日期。
Get-CimInstance -ClassName Win32_OperatingSystem | Select LastBootUpTime
输出结果
LastBootUpTime -------------- 9/29/2020 8:12:08 AM
如果我们检查上述输出的数据类型,由于输出格式的原因,它应该为DateTime。
(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.Gettype()
输出结果
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True DateTime System.ValueType
现在,我们需要以天-小时-分钟格式显示系统的正常运行时间。因此,我们将比较当前日期/时间与启动日期/时间之间的差异。
$bootuptime = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime $CurrentDate = Get-Date $uptime = $CurrentDate - $bootuptime $uptime
输出结果
Days : 6 Hours : 0 Minutes : 17 Seconds : 38 Milliseconds : 301 Ticks : 5194583016830 TotalDays : 6.01224886207176 TotalHours : 144.293972689722 TotalMinutes : 8657.63836138333 TotalSeconds : 519458.301683 TotalMilliseconds : 519458301.683
从输出中,我们可以说服务器的运行时间为6天17分钟。我们还可以如下编写输出。
Write-Output "Server Uptime --> Days: $($uptime.days), Hours: $($uptime.Hours), Minutes:$($uptime.Minutes)"
输出结果
Server Uptime --> Days: 6, Hours: 0, Minutes:17
要检查远程计算机的正常运行时间,请在命令中使用-ComputerName参数。例如,
$servers = "Test1-Win2k12","Test1-Win2k16","ADDC" $currentdate = Get-Date foreach($server in $servers){ $Bootuptime = (Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $server).LastBootUpTime $uptime = $currentdate - $Bootuptime Write-Output "$server Uptime : $($uptime.Days) Days, $($uptime.Hours) Hours, $($uptime.Minutes) Minutes" }
输出结果
Test1-Win2k12 Uptime : 5 Days, 22 Hours, 50 Minutes Test1-Win2k16 Uptime : 5 Days, 23 Hours, 12 Minutes ADDC Uptime : 6 Days, 2 Hours, 9 Minutes