How to configure a service auto-restart after failure with PowerShell
On a Windows system, in the Service console, there is a recovery tab to configure actions for a service in case of failure.
How can I configure this with PowerShell?
Solution 1:
There is currently no native PowerShell cmdlet to manage the service recovery.
However, to auto-restart a service when it fails you can use SC
.
(In a PowerShell prompt you must precede it with & and use the full name sc.exe
)
& sc.exe failure msftpsvc reset= 30 actions= restart/5000
The official documentation is on Microsoft Docs under Sc Failure
Solution 2:
Abstract from https://evotec.xyz/set-service-recovery-options-powershell/
function Set-ServiceRecovery{
[alias('Set-Recovery')]
param
(
[string] [Parameter(Mandatory=$true)] $ServiceDisplayName,
[string] [Parameter(Mandatory=$true)] $Server,
[string] $action1 = "restart",
[int] $time1 = 30000, # in miliseconds
[string] $action2 = "restart",
[int] $time2 = 30000, # in miliseconds
[string] $actionLast = "restart",
[int] $timeLast = 30000, # in miliseconds
[int] $resetCounter = 4000 # in seconds
)
$serverPath = "\\" + $server
$services = Get-CimInstance -ClassName 'Win32_Service' -ComputerName $Server| Where-Object {$_.DisplayName -imatch $ServiceDisplayName}
$action = $action1+"/"+$time1+"/"+$action2+"/"+$time2+"/"+$actionLast+"/"+$timeLast
foreach ($service in $services){
# https://technet.microsoft.com/en-us/library/cc742019.aspx
$output = sc.exe $serverPath failure $($service.Name) actions= $action reset= $resetCounter
}
}
Set-ServiceRecovery -ServiceDisplayName "Pulseway" -Server "MAIL1"