简体   繁体   English

并行启动服务

[英]Start services in parallel

I have a script which checks if certain service on different servers is up, if it is not, the script should start the service. 我有一个脚本,该脚本检查不同服务器上的某些服务是否启动,否则,脚本应启动该服务。

The problem is, it doesn't start the services in parallel, instead it waits until each service is started. 问题是,它不会并行启动服务,而是等待直到每个服务都启动。

Code: 码:

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

I know it's due to the way the script is written, but maybe some of you have any suggestions how to make it better? 我知道这是由于脚本的编写方式引起的,但也许有些人对如何改进脚本有任何建议?

Cheers! 干杯!

Here is an example of parallel processing using Powershell and Workflows: 这是使用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
        }
    }
}

Using Powershell V2 and jobs 使用Powershell V2和作业

Untested code, but should be close: 未经测试的代码,但应接近:

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM