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

前端 未结 5 964
难免孤独
难免孤独 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:51

    In your ForEach loop you'll want to grab the output generated by the Jobs already running.

    Example Not Tested

    $sb = {
         "Starting Job on $($args[0])"
         #Do something
         "$($args[0]) => Do something completed successfully"
         "$($args[0]) => Now for something completely different"
         "Ending Job on $($args[0])"
    }
    Foreach($computer in $computers){
        Start-Job -ScriptBlock $sb -Args $computer | Out-Null
        Get-Job | Receive-Job
    }
    

    Now if you do this all your results will be mixed. You might want to put a stamp on your verbose output to tell which output came from.

    Or

    Foreach($computer in $computers){
        Start-Job -ScriptBlock $sb -Args $computer | Out-Null
        Get-Job | ? {$_.State -eq 'Complete' -and $_.HasMoreData} | % {Receive-Job $_}
    }
    while((Get-Job -State Running).count){
        Get-Job | ? {$_.State -eq 'Complete' -and $_.HasMoreData} | % {Receive-Job $_}
        start-sleep -seconds 1
    }
    

    It will show all the output as soon as a job is finished. Without being mixed up.

提交回复
热议问题