【问题标题】:Start services in parallel并行启动服务
【发布时间】:2014-12-08 07:36:19
【问题描述】:

我有一个脚本,它检查不同服务器上的某些服务是否启动,如果没有,脚本应该启动该服务。

问题是,它不会并行启动服务,而是等待每个服务启动。

代码:

$server_list = Get-Content -path D:\Path\list_of_servers.txt

$server_list | foreach { 
 (Get-Service -Name '*Service Name*' -computername $_) | Where-Object {$_.status -eq "Stopped"} | Set-Service -Status Running
}

我知道这是由于脚本的编写方式,但也许你们中的一些人有什么建议可以让它变得更好?

干杯!

【问题讨论】:

  • 您运行的是哪个版本的 Powershell?对于 V3 和 V4,您可以使用 foreach -parallel
  • 你看过使用Start-Job吗?
  • @MickyBalladelli 遗憾的是,我们正在使用 V2
  • @ST8Z6FR57ABE6A8RE9UF 不,我会检查一下。
  • 我在答案中添加了一个工作示例。

标签: powershell remote-access


【解决方案1】:

以下是使用 Powershell 和 Workflows 进行并行处理的示例:

$server_list = Get-Content -path D:\Path\list_of_servers.txt
workflow MyWorkflow
{
    foreach -parallel($s in $server_list) { 
        inlinescript { (Get-Service -Name '*Service Name*' -PSComputerName $s) | Where-Object {$_.status -eq "Stopped"} | Set-Service -Status Running
        }
    }
}

使用 Powershell V2 和作业

未经测试的代码,但应该接近:

$server_list = Get-Content -path D:\Path\list_of_servers.txt

$maxJobs = 5
$scriptblock = { 
(Get-Service -Name $args[1] -ComputerName $args[0]) | Where-Object {$_.status -eq "Stopped"} | Set-Service -Status Running
}

foreach ($s in $server_list)
{
    $arguments = @($s, $service)

    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
    while ($running.Count -gt ($maxJobs -1)) {
        $done = Get-Job | Wait-Job -Any
        $running = @(Get-Job | ? {$_.State -eq 'Running'})
    }   
    start-job -scriptblock $scriptblock -ArgumentList $arguments
}
Get-Job | Wait-Job
Get-Job | Receive-Job

【讨论】:

  • 它会起作用,但是从资源的角度来看,为了重新启动服务而启动后台作业似乎有点笨拙。
猜你喜欢
  • 2011-05-08
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 2015-05-07
  • 1970-01-01
  • 2016-09-07
相关资源
最近更新 更多