6

I am have a really hard time getting this to work. Hopefully someone can help me out!

I am currently working on a Powershell deployment script for a service. After installing the service, I'd like to set the Service Recovery options to "Restart the Service" every time the service crashes after 0 minutes.

Does anyone know how to do this using Powershell to set these options for remote machine?

Max Alexander
  • 5,471
  • 6
  • 38
  • 52

6 Answers6

8

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.

Mohammad Nadeem
  • 9,134
  • 14
  • 56
  • 82
6

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!

4

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.

MadBoy
  • 10,824
  • 24
  • 95
  • 156
3

If it were a local service you could use sc.exe however you want to change settings for remote service. One way to do this is to set the registry keys directly using remote registry:

Here are the settings you'll need:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<ServiceShortName>    
Value Name                Data Type    Description
FailureActions            REG_BINARY   Configuration information for 1st, 2nd, and subsequent failures.

What I would do is setup the service recovery options the way you want them and then read the registry value FailureActions

$actions = get-itemproperty hklm:\system\currentcontrolset\services\<ServiceShortName> | select -Expand FailureActions

Then serialize this to disk for use later:

$actions | Export-Clixml C:\actions.xml

When your ready to remotely configure the service, re-read the FailureActions data, connect to the remote registry and set the registry key:

$actions2 | Import-Clixml C:\actions.xml
$key = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, "<RemoteComputerName>")
$key2 = $key.OpenSubKey('SYSTEM\CurrentControlSet\Services\<ServiceShortName>', $true)
$key2.SetValue('FailureActions', ([byte[]] $actions))
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
1

The Carbon library has a pretty comprehensive Install-Service cmdlet which lets you specify recovery actions, e.g. (adapted from the Install-Service doc page):

Install-Service -Name DeathStar -Path C:\ALongTimeAgo\InAGalaxyFarFarAway\DeathStar.exe -OnFirstFailure Restart -RestartDelay 10000

This will install the DeathStar service and restart with a 10 second delay after the first failure.

Lucas Wilson-Richter
  • 2,274
  • 1
  • 18
  • 24
0

jborean93 has created a custom type that exposes the native C# service objects and methods to PowerShell. The included Get-ServiceRecovery and Set-ServiceRecovery functions make it easy to view and change service recovery settings within PowerShell. https://gist.github.com/jborean93/889288b56087a2c5def7fa49b6a8a0ad

.\ServiceRecovery.ps1
Get-ServiceRecovery -ComputerName 'MyComputer' -Name 'MyService'
Set-ServiceRecovery -ComputerName 'MyComputer' -Name 'MyService' -Actions @('RunCommand', 'Restart', 'None') -Command '"C:\Windows\System32\cmd.exe" /c echo hi'

For the DSC fans out there, looks like this functionality is also being worked into xPSDesiredStateConfiguration (xService) at some point in the future. https://github.com/dsccommunity/xPSDesiredStateConfiguration/pull/679