Set Remote Service's Recovery Options using Powershell? Set Remote Service's Recovery Options using Powershell? powershell powershell

Set Remote Service's Recovery Options using Powershell?


You can write a powershell function using sc.exe as explained here. The function will look something like:

function Set-Recovery{    param    (        [string]         [Parameter(Mandatory=$true)]        $ServiceName,        [string]        [Parameter(Mandatory=$true)]        $Server    )    sc.exe "\\$Server" failure $ServiceName reset= 0 actions= restart/0 #Restart after 0 ms}

And you can call the function like:

Set-Recovery -ServiceName "ServiceName" -Server "ServerName"

Note: The account you are running the script must have admin rights on the remote server.


I've taken @Mohammad Nadeem idea and expanded it with full support of all actions instead of just primary one. I've also used Display Name for service rather than service name so it's a bit easier to provide parameter.

function 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' | 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-Recovery -ServiceDisplayName "Pulseway" -Server "MAIL1"

I've created a blog post about it: https://evotec.xyz/set-service-recovery-options-powershell/. I've not tested this in other scenarios than restart of service. Probably would need some work to support all scenarios.


Please, simplify..

Use the oldiest sc.exe in powershell code. Is more easy and fully functional.

sc.exe failure "ServiceName" actions= restart/180000/restart/180000/reboot/180000 reset= 86400;

The restarts, in milliseconds. And the last reset, in seconds.

(Each restart in 3 min, and the reset in 1 day)

Bye!