Powershell自动服务重启

时间:2019-05-13 12:12:23

标签: powershell service restart

我在一台特定服务器上的prtg探测服务器上有问题。 在此服务器中,由于prtg服务,CPU使用率达到90%,需要重新启动。 当CPU使用率达到90%时,如何自动重新启动prtg服务?

我当时想创建一个有条件的脚本,但是无法完成。

-Set-Service [service name] -startuptype automatic

2 个答案:

答案 0 :(得分:0)

如果您使用的是PowerShell 5.x,则可以使用Get-Counter来获取CPU使用率。在服务器上尝试以下检查:

$peridiocallyChecks = {
   # Check if logging source is available, if not add it
   if (!(Get-EventLog -Source "CPU supervision" -LogNameApplication)){
       New-EventLog -LogName Application -Source "CPU supervision"
   }

   $cpuUsage = [double] (Get-Counter '\Processor(_Total)\% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue)

   if ($cpuUsage -gt 90) {
       Write-EventLog -LogName "Application" -Source "CPU supervision" -EntryType Information -EventId 1 -Message "CPU usage is $cpuUsage. Going to stop service"
       Stop-Service "yourServiceName"
       # Some cooldown time for the service to shutdown
       Start-Sleep -Seconds 10
       Start-Service "yourServiceName"
       Write-EventLog -LogName "Application" -Source "CPU supervision" -EntryType Information -EventId 1 -Message "Restarted service"
   }
}

# Trigger every hour
$trigger = New-JobTrigger -Once -At "9/21/2012 0am" -RepetitionInterval (New-TimeSpan -Hour 12) -RepetitionDuration ([TimeSpan]::MaxValue)

Register-ScheduledJob -Name "CPUCheck" -Trigger $trigger -Scriptblock $peridiocallyChecks

检查有关工作的以下链接:

希望有帮助

答案 1 :(得分:0)

要获得PRTG的CPU使用率,可以使用以下powershell行

Get-Counter '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| where {$_.InstanceName -match "prtg" }

然后可以将其与您的限制(90%)进行比较,并确定是否要在powershell中运行以下命令

restart-service PRTG

那将是答案,现在我对您的情况的建议

  • 重启探针永远无法解决CPU负载过高的问题-如果可能,尝试添加更多CPU
  • 减少传感器数量
  • 识别长时间运行的传感器或CPU繁重的传感器,并对其进行优化或删除/替换,以轻巧的替代方案
  • 如果不能选择添加CPU或以上点,则将另一个探针添加到另一台机器上-这样,您可以将传感器分为两个探针