I have a list of commands and I'm trying to invoke them using Start-Job each. Each command should return an array of objects. How do I wait on each command's array and combine them after all commands are done running? I am using PS 5.1
cmds = "Command-One", "Command-Two"
foreach cmd in cmds
{
Start-Job -ScriptBlock { cmd }
}
A simple example:
Note how the input command strings (designed to output two numbers each) must be converted to script blocks via
[scriptblock]::Create()so that they can be passed toStart-Job's-ScriptBlockparameter.However, it is preferable and simpler to provide the commands as script block to begin with; using script-block literals (
{ ... }):If you want to separate the timing of creating the jobs from waiting for their completion / collecting their output:
All variants launch two jobs and (directly or indirectly) pipe the job objects output by
Start-JobtoReceive-Job, which collects their output (see bottom section for details):-Waitadditionally waits for both jobs to complete, thereby ensuring that all job output has been received and output-Wait,Receive-Jobcollects all output produced so far, and returns right away, so that multiple calls may be necessary; optionally, you can collect output without consuming it (-Keep).-AutoRemoveJobautomatically cleans up the jobs afterwards, which by definition have terminated by then.Note that there's also:
Wait-Jobwhich performs waiting only, optionally for a given state (-State), and optionally with a timeout (-Timeout), necessitating a separateReceive-Jobcall to collect output.Remove-Jobwhich removes jobs only, optionally including their forceful termination (-Force), if they haven't completed yet.How
Receive-Jobcollects output:Jobs never create direct output to the caller's console - all output, even to output streams other than the success stream, such as with
Write-Host- are collected byReceive-Joband routed to the corresponding output streams of the caller.Objects emitted by jobs to the success output stream (i.e. data output) are decorated with properties identifying the job of origin:
Properties containing auto-generated GUIDs identifying the job.
.RunspaceId.PSSourceJobInstanceId(only while the job is running, seeminlgy)Start-Jobvia-Nameis not reflected here, so there is no obvious way to correlate output objects with the job they came from - see below.Two more properties that are primarily of interest in PowerShell's remoting (whose infrastructure background jobs partially use):
.PSComputerName: always'localhost'in background jobs.PSShowComputerName: always$falsein background jobs; a hint to the formatting system as to whether to show the value of the.PSComputerNameproperty.To illustrate the points above:
If you want to collect and emit output for each job separately: