我很難讓這個工作。希望有人能幫助我!使用PowerShell設置遠程服務的恢復選項?
我目前正在開發一個服務的Powershell部署腳本。安裝服務後,我想在每次服務崩潰後0分鐘時將服務恢復選項設置爲「重新啓動服務」。
有誰知道如何使用Powershell爲遠程機器設置這些選項?
我很難讓這個工作。希望有人能幫助我!使用PowerShell設置遠程服務的恢復選項?
我目前正在開發一個服務的Powershell部署腳本。安裝服務後,我想在每次服務崩潰後0分鐘時將服務恢復選項設置爲「重新啓動服務」。
有誰知道如何使用Powershell爲遠程機器設置這些選項?
如果是本地服務,您可以使用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))
的Carbon庫有一個非常全面的Install-Service
cmdlet的,它可以讓你指定恢復行動,例如(改編自Install-Service doc page):
Install-Service -Name DeathStar -Path C:\ALongTimeAgo\InAGalaxyFarFarAway\DeathStar.exe -OnFirstFailure Restart -RestartDelay 10000
這將安裝DeathStar
服務,並與第一次失敗之後10秒的延遲重新啓動。
您可以使用sc.exe編寫powershell函數,如解釋here所述。該功能將類似於:
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"
注:該帳戶正在運行的腳本必須在遠程服務器上管理員權限。
我已經採納了@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-service-recovery-options-powershell/。我沒有在服務重啓的其他場景中測試過。可能需要一些工作來支持所有情況。
請注意,'sc.exe'能夠對遠程服務器進行更改,前提是您有辦法進行身份驗證。 – 2016-02-29 14:55:15