首页 > 解决方案 > 如何使用 Powershell 找出服务何时重新启动

问题描述

我有一个如下所示的 Powershell 脚本,我想使用它来找出服务的正常运行时间。

如果机器本身重新启动或服务停止/启动,此脚本能够成功捕获服务的正常运行时间。

但是当服务停止时,它没有捕获自停止以来的正确时间,并且我仍然获得正常运行时间,就像机器重新启动时一样。

有什么帮助吗?提前致谢!

function Get-ServiceUptime
{
  param([string]$Name)

  # Prepare name filter for WQL
  $Name = $Name -replace "\\","\\" -replace "'","\'" -replace "\*","%"

  # Fetch service instance
  $Service = Get-CimInstance -ClassName Win32_Service -Filter "Name LIKE '$Name'"

  # Use ProcessId to fetch corresponding process
  $Process = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $($Service.ProcessId)"

  # Calculate uptime and return
  return (Get-Date) - $Process.CreationDate
}

$uptime = Get-ServiceUptime -Name MyServiceName

标签: windowspowershellservice

解决方案


您可以使用 Windows 事件来了解服务的启动时间。服务本身不会跟踪它何时重新启动......

(Get-EventLog -LogName "System" -Source "Service Control Manager" -EntryType "Information" -Message "*Print Spooler service*running*" -Newest 1).TimeGenerated

这不会告诉您服务是否仍在运行,而是告诉您上次服务是否启动。您需要检查显示它何时停止的事件并比较日期以查看它是否仍在运行以及它上次出现的时间。

另请注意,Windows 日志会轮换,因此某些运行时间超过最旧记录的服务将不可用。

上面的例子取自这里


推荐阅读