Search code examples
powershellservicerecovery

Set Remote Service's Recovery Options using Powershell?


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?


Solution

  • 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))