Powershell - Start ordered sequence of services

走远了吗. 提交于 2019-12-11 19:26:49

问题


I need to start an ordered sequence of services, i need that each service will be up and running before try to start the next one, how can I achieve this in Powershell? How can I wait for the stop too?

Thanks,

DD


回答1:


If you have a list of service names (say in an array), then foreach service:

  1. Get its status
  2. If not running, then start it
  3. With a delay in the loop, check its status until it is running

The key is likely to be handling all the possibilities for #3 including the service failing.

But an outline would be something like (without handling the error cases):

$serviceNames | Foreach-Object -Process {
  $svc = Get-Service -Name $_
  if ($svc.Status -ne 'Running') {
    $svc.Start()
    while ($svc.Status -ne 'Running') {
      Write-Output "Waiting for $($svc.Name) to start, current status: $($svc.Status)"
      Start-Sleep -seconds 5
    }
  }
  Write-Output "$($svc.Name) is running"
}

Get-Service returns an instance of System.ServiceProcess.ServiceController which is "live"—indicating the current state of the service, not just the state when the instance was created.

A similar stop process would replace "Running" with "Stopped" and the "Start" call with "Stop". And, presumably, reverse the order of the list of services.




回答2:


Don't do this manually (regardless of scripting language). Define proper dependencies between the services and Windows will start/stop them in the correct order. You can use the sc utility to define the dependencies:

sc config Svc2 depend= Svc1

If a service should depend on more than one other service you separate the dependent services with forward slashes:

sc config Svc5 depend= Svc3/Svc4

Note that the = must be followed by a space and must not be preceded by one.




回答3:


To stop Services

$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -eq "Running")}
 Foreach-Object {$_.(Stop-Service $serviceNames)}

To start Services

$ServiceNames = Get-Service | where {($_.Name -like "YourServiceNameHere*")-and ($_.Status -ne "Running")}
Foreach-Object {$_.(Start-Service $ServiceNames)}


来源:https://stackoverflow.com/questions/18890389/powershell-start-ordered-sequence-of-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!