当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 获取计算机上次启动时间或正常运行时间

作者:精品下载站 日期:2024-12-14 08:14:09 浏览:16 分类:玩电脑

使用 PowerShell 获取计算机上次启动时间或正常运行时间


您可能需要在上次启动时间或计算机正常运行时间附近发生逻辑。或者您可能只是想将其显示给用户。 PowerShell 提供了一种使用 Get-WMIObject commandlet 来完成此操作的简单方法。我将向您展示如何获取计算机的上次启动时间和当前运行时间。我还将说明如何使用一个函数来远程确定任何计算机的正常运行时间。

步骤#1:第一步是获取上次启动时间所需的 WMI 对象类和属性。

Get-WmiObject -Class win32_operatingsystem -Property LastBootUpTime

步骤#2:第二步是为该对象分配一个变量,然后将 LastBootUpTime 的属性转换为日期和时间对象。

$os = Get-WmiObject -Class win32_operatingsystem
$os.ConvertToDateTime($os.LastBootUpTime)

步骤#3:第三步是确定计算机的正常运行时间。

$os = Get-WmiObject -Class win32_operatingsystem
$os.ConvertToDateTime($os.LastBootUpTime)
(get-date) - $os.ConvertToDateTime($os.LastBootUpTime)

步骤#4:我们现在可以结合上次启动时间和总启动时间从控制台查看

$os = Get-WmiObject win32_operatingsystem
$uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
Write-Output ("Last boot: " + $os.ConvertToDateTime($os.LastBootUpTime))
Write-Output ("Uptime: " + $uptime.Days + " Days " + $uptime.Hours + " Hours " + $uptime.Minutes + " Minutes") 

步骤#5:以下函数是根据上面的脚本创建的函数,可以执行该函数来检索当前计算机的启动时间。

Function Get-Uptime {
$os = Get-WmiObject win32_operatingsystem -ErrorAction SilentlyContinue
$uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
Write-Output ("Last boot: " + $os.ConvertToDateTime($os.LastBootUpTime) )
Write-Output ("Uptime   : " + $uptime.Days + " Days " + $uptime.Hours + " Hours " + $uptime.Minutes + " Minutes" )
}

Get-Uptime

步骤#6:以下函数是一个稍微修改为接受 ComputerName 参数的函数,可以执行该函数以通过指定主机名检索当前计算机的启动时间或不同计算机的启动时间。

Function Get-Uptime {
Param ( [string] $ComputerName = $env:COMPUTERNAME )
$os = Get-WmiObject win32_operatingsystem -ComputerName $ComputerName -ErrorAction SilentlyContinue
 if ($os.LastBootUpTime) {
   $uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
   Write-Output ("Last boot: " + $os.ConvertToDateTime($os.LastBootUpTime) )
   Write-Output ("Uptime   : " + $uptime.Days + " Days " + $uptime.Hours + " Hours " + $uptime.Minutes + " Minutes" )
  }
  else {
    Write-Warning "Unable to connect to $computername"
  }
}

Get-Uptime -ComputerName RemoteComputerHostName

请随时发表评论或对 PowerShell 解决方案提出任何请求。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯