简体   繁体   中英

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:

$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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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