How to execute parallel/ Threaded jobs in PowerShell


Many times we need to work in parallel when executing the Powershell commands. Today in this post I will tell how we can execute the commands in parallel. 

In my case, I have used these parallel jobs for the migration of SharePoint On-Prem to SharePoint Online using Sharegate, executing multiple instances and then monitoring those instances to initiate as soon as any of the instances is finished executing.

Step 1: Installing the Module

To leverage the benefit of the parallel jobs, we need to install the Module so to install the module, execute the following command

Install-Module -Name "ThreadJob" -Scope AllUsers

Once the module is installed, then you are ready to go.

Step 2: Execute Parallel Jobs

Now you can start parallel jobs in the background. Here is the sample for executing the parallel jobs

$Job = Start-ThreadJob -FilePath ".\PowershellScript.ps1" -ArgumentList @($param1, $param2) -Name $TitleOfJob

Here you need to pass following

  • File Path: Path to the PowerShell script that needs to be executed
  • Argument List: Arguments if any needs to be passed to the executing script
  • Title: Title of the job

Step 3: Check for Job Completion

Many times we need to check if the job execution has finished. Below is the command to check on the status of the job

Get-Job -State Running 

Step 4: How to wait for the Job to finish

If we need to wait for the job to get finish and then do some processing, then you can continuously check the job status using the above command once the job status is completed do your next task

$runningBackgroundJobs = Get-Job -State Running 
while($runningBackgroundJobs.Count -gt 0){
    Start-Sleep -Seconds 1
    $runningBackgroundJobs = Get-Job -State Running

Or you can check on the specific Job by filtering the results based on the Name of the Job or ID of the Job

Get-Job -State Running | Where-Object { $_.Id -eq 123 } Get-Job -State Running | Where-Object { $_.Name -eq "Title of the Job" }

Hope these commands will help you execute the parallel jobs and help you execute the task more efficiently.

Happy Coding..!!

Sumit Kanchan


Popular posts from this blog

Rename Folder using Microsoft Flow / Power Automate in a Document Library in SharePoint Online

Power Automate: How to Add "New Line" to the text in SharePoint multiline text field

Power Automate: Rename file in SharePoint Online