Powershell: Run multiple jobs in parralel and view streaming results from background jobs

前端 未结 5 953
难免孤独
难免孤独 2020-12-09 17:13

Overview

Looking to call a Powershell script that takes in an argument, runs each job in the background, and shows me the verbose output.

5条回答
  •  伪装坚强ぢ
    2020-12-09 17:47

    Not a new question but I feel it is missing an answer including Powershell using workflows and its parallel possibilities, from powershell version 3. Which is less code and maybe more understandable than starting and waiting for jobs, which of course works good as well.

    I have two files: TheScript.ps1 which coordinates the servers and BackgroundJob.ps1 which does some kind of check. They need to be in the same directory.

    The Write-Output in the background job file writes to the same stream you see when starting TheScript.ps1.

    TheScript.ps1:

    workflow parallelCheckServer {
        param ($Servers)
        foreach -parallel($Server in $Servers)
        {
            Invoke-Expression -Command ".\BackgroundJob.ps1 -Server $Server"
        }
    }
    
    parallelCheckServer -Servers @("host1.com", "host2.com", "host3.com")
    
    Write-Output "Done with all servers."
    

    BackgroundJob.ps1 (for example):

    param (
        [Parameter(Mandatory=$true)] [string] $server
    )
    
    Write-Host "[$server]`t Processing server $server"
    Start-Sleep -Seconds 5
    

    So when starting the TheScript.ps1 it will write "Processing server" 3 times but it will not wait for 15 seconds but instead 5 because they are run in parallel.

    [host3.com]  Processing server host3.com
    [host2.com]  Processing server host2.com
    [host1.com]  Processing server host1.com
    Done with all servers.
    

提交回复
热议问题