windows - 如何使用 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
解决方案
您可以使用 Windows 事件来了解服务的启动时间。服务本身不会跟踪它何时重新启动......
(Get-EventLog -LogName "System" -Source "Service Control Manager" -EntryType "Information" -Message "*Print Spooler service*running*" -Newest 1).TimeGenerated
这不会告诉您服务是否仍在运行,而是告诉您上次服务是否启动。您需要检查显示它何时停止的事件并比较日期以查看它是否仍在运行以及它上次出现的时间。
另请注意,Windows 日志会轮换,因此某些运行时间超过最旧记录的服务将不可用。
上面的例子取自这里
推荐阅读
- flutter - 如何从 json 列表中返回对象?
- asp.net - 旧的 Asp.Net Web 表单应用程序不记录通过 IIS URL 重写模块到达的 Web 请求
- python - Scrapy:由于多个 for 循环,重复的项目字段
- javascript - setPointerCapture 在 Chrome 和 Firefox 中的行为不同
- maven - Allure Test NG 报告 TestBody 缺失
- python - 使用现有 Teradata 数据库定义模型以供烧瓶应用程序使用时出现“QVCI 功能已禁用”错误
- css - 当包含在 iframe 中时,固定位置菜单不起作用
- onedrive - 如何将 API 密钥限制为单向写入而不读取单个 OneDrive 文件夹?
- html - 字段对齐未按预期工作
- javascript - 从 NodeJS 中的变量打印对象值