我有一个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
发布于 2020-06-08 12:50:02
您可以使用Windows事件找出服务启动的时间。服务本身不会跟踪它何时重新启动...
(Get-EventLog -LogName "System" -Source "Service Control Manager" -EntryType "Information" -Message "*Print Spooler service*running*" -Newest 1).TimeGenerated
这不会告诉您服务是否仍在运行,但会告诉您它上次运行的时间。您需要检查显示它何时停止的事件,并比较日期以查看它是否仍在运行以及它最后一次出现的时间。
还要注意的是,windows日志是循环的,因此一些运行时间超过最早记录的服务将不可用。
上面的例子取自
https://stackoverflow.com/questions/62255107
复制相似问题