I am trying to restart specific service when cpu usage come to 80%. I am using job trigger and try to get logs but I could not restart to service.
$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"
}
#Getting CPU usage e.g 45.3434242423
$cpuUsage = [double] (Get-Counter '\Processor(_Total)\% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue)
if ($cpuUsage -gt 80) {
Write-EventLog -LogName "Application" -Source "CPU supervision" -EntryType Information -EventId 1 -Message "CPU usage is $cpuUsage. Going to stop service"
Stop-Service "service name"
# Some cooldown time for the service to shutdown
Start-Sleep -Seconds 10
Start-Service "service name"
Write-EventLog -LogName "Application" -Source "CPU supervision" -EntryType Information -EventId 1 -Message "Restarted service"
}
Get-EventLog -Source "CPU supervision" -LogName Application
}
# Trigger every hour
$trigger = New-JobTrigger -Once -At "17/05/2019 0am" -RepetitionInterval (New-TimeSpan -Hour 12) -RepetitionDuration ([TimeSpan]::MaxValue)
Register-ScheduledJob -Name "CPUCheck23" -Trigger $trigger -Scriptblock $peridiocallyChecks