如何使用Powershell重新启动服务

问题描述 投票:0回答:1

我有一个如下所示的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 powershell service ps1
1个回答
0
投票

您可以使用Windows事件来确定服务启动的时间。服务本身无法跟踪何时重新启动...

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

以上示例取自here

© www.soinside.com 2019 - 2024. All rights reserved.