Michael M. Michael M. - 8 months ago 31
PowerShell Question

PowerShell background jobs (multiple .cmd files at the same time)

I'm trying to synchronize different tasks at the same the time in PowerShell because they each take around 2-4 hours. The Script i have right now just processes each task one after another. I know there is an option called background jobs in PowerShell. Is there a way to transform the following code so it processes multiple .cmd files at the same time?

$answer= $finalcheck.popup("text",0,"text",4)
If($answer-eq 6) {
[Windows.Forms.MessageBox]::Show("text", "Information", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
if ($checkBox1.Checked) {
& K:\sample.cmd
}catch [System.Exception]{

if ($checkBox2.Checked) {
& K:\sample2.cmd
}catch [System.Exception]{


You can use Start-Job:

$job = Start-Job { & K:\sample.cmd }

At this point you are likely to need to add some code to watch the state of jobs you've started. Potentially you can periodically inspect $job.State.

Extending on this, you might refuse to start a job of the same type if one is already running.

In addition to Start-Job you should take a look at:

  • Get-Job - To get any jobs (running or otherwise)
  • Receive-Job - To get results back
  • Remove-Job - To remove a job once you're finished with it.
  • Stop-Job - To stop the job if you need to kill it.