Powershell - 启动有序的服务序列

时间:2013-09-19 09:01:51

标签: windows powershell service database-administration

我需要启动一个有序的服务序列,我需要在尝试启动下一个服务之前启动并运行每个服务,我怎样才能在Powershell中实现这一点?我怎么能等待停止呢?

谢谢,

DD

3 个答案:

答案 0 :(得分:2)

不要手动执行此操作(无论脚本语言如何)。定义服务之间的正确依赖关系,Windows将以正确的顺序启动/停止它们。您可以使用sc实用程序来定义依赖项:

sc config Svc2 depend= Svc1

如果服务应依赖于多个其他服务,则使用正斜杠分隔依赖服务:

sc config Svc5 depend= Svc3/Svc4

请注意,= 必须后跟一个空格,不能前面加一个。

答案 1 :(得分:1)

如果您有服务名称列表(比如数组),那么foreach服务:

  1. 获取其状态
  2. 如果没有运行,请启动它
  3. 如果循环延迟,请检查其状态,直至其运行
  4. 密钥很可能是处理#3的所有possibilities,包括服务失败。

    但是大纲就像(没有处理错误情况):

    $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返回System.ServiceProcess.ServiceController的实例,它是“实时” - 指示服务的当前状态,而不仅仅是实例创建时的状态。

    类似的停止过程会将“正在运行”替换为“停止”,将“启动”调用替换为“停止”。并且,可能会颠倒服务列表的顺序。

答案 2 :(得分:0)

停止服务

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

要启动服务

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