使用 Powershell 设置远程服务的恢复选项?

发布于 2025-01-05 07:56:10 字数 150 浏览 1 评论 0原文

我真的很难让它发挥作用。希望有人可以帮助我!

我目前正在为一项服务编写 Powershell 部署脚本。安装服务后,我想将服务恢复选项设置为每次服务在 0 分钟后崩溃时“重新启动服务”。

有谁知道如何使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

∞觅青森が 2025-01-12 07:56:10

您可以使用 sc.exe 编写 powershell 函数,如此处所述。该函数将类似于:

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
}

您可以像这样调用该函数:

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

注意:运行脚本的帐户必须在远程服务器上具有管理员权限。

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.

花期渐远 2025-01-12 07:56:10

请简化...

在powershell代码中使用最古老的sc.exe。更加简单且功能齐全。

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

重新启动(以毫秒为单位)。最后一次重置,以秒为单位。

(每次重启3分钟,重置1天)

再见!

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!

蒲公英的约定 2025-01-12 07:56:10

我采纳了 @Mohammad Nadeem 的想法,并通过对所有行动(而不仅仅是主要行动)的全力支持来扩展它。我还使用了服务的显示名称而不是服务名称,因此提供参数更容易一些。

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"

我创建了一篇关于它的博客文章: https://evotec.xyz/set-服务恢复选项-powershell/。除了重新启动服务之外,我还没有在其他场景中对此进行过测试。可能需要一些工作来支持所有场景。

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.

焚却相思 2025-01-12 07:56:10

如果它是本地服务,您可以使用 sc.exe,但是您想更改远程服务的设置。一种方法是使用远程注册表直接设置注册表项:

以下是您需要的设置:

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

我要做的是以您想要的方式设置服务恢复选项,然后读取注册表值FailureActions

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

然后将其序列化到磁盘以供以后使用:

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

当您准备好远程配置服务时,重新读取 FailureActions 数据,连接到远程注册表并设置注册表项:

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

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))
七度光 2025-01-12 07:56:10

Carbon 库有一个非常全面的 Install-Service cmdlet,可让您指定恢复操作,例如(改编自 Install-Service 文档页面):

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

这将安装DeathStar 服务并重新启动第一次失败后延迟 10 秒。

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.

一笔一画续写前缘 2025-01-12 07:56:10

jborean93 创建了一个自定义类型,将本机 C# 服务对象和方法公开给 PowerShell。附带的 Get-ServiceRecovery 和 Set-ServiceRecovery 函数使您可以轻松地在 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'

对于 DSC 粉丝来说,看起来像这样未来某个时候,该功能也会被纳入 xPSDesiredStateConfiguration (xService) 中。
https://github.com/dsccommunity/xPSDesiredStateConfiguration/pull/679

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文