Asynchronous Operations in PowerShell

PowerShell is administrator’s best friend. A long running job can be made to run faster by breaking them into logical functionalities and run those in an asynchronous manner. This will help speed up the processing of tasks from PowerShell.

We usually have the asynchronous operations code written in server languages like C#. Same can be achieved in scripting languages like PowerShell.

For example, when we are dealing with a task to copy large amount of files from multiple source location.

A simple copy operation

  1. $source = "\\RemoteServer\c$\fileshares"  
  2. $target = "D:\CopyTest"   
  3. Copy-Item -Path $source -Destination $target -Recurse Verbose  
Async operation
  1. As a next step, we will wrap up this in a Start-Job  
  2. $copyJob = Start-Job –ScriptBlock {  
  3.    $source = "\\RemoteServer\c$\fileshares"  
  4.    $target = "D:\CopyTest"   
  5.    Copy-Item -Path $source -Destination $target -Recurse Verbose  
  6. }  
  1. Wait-Job $copyJob  
This will help running the file copy operations in an asynchronous manner.

Waiting for job to complete

We can wait for a job to complete using Receive-Job.
  1. Receive-Job $copyJob  
Real time example

To carry out multiple copy operations asynchronously:
  1. $copyJob1 = Start - Job– ScriptBlock  
  2. {  
  3.     $source = "\\RemoteServer\c$\fileshares"  
  4.     $target = "D:\CopyTest"  
  5.     Copy - Item - Path $source - Destination $target - Recurse Verbose  
  6. }#  
  7. Code here will run async  
  8. $copyJob2 = Start - Job– ScriptBlock  
  9. {  
  10.     $source = "\\RemoteServer\c$\Shared"  
  11.     $target = "D:\CopyTest"  
  12.     Copy - Item - Path $source - Destination $target - Recurse Verbose  
  13. }#  
  14. Code here will run async  
  15. Wait - Job $copyJob1  
  16. Wait - Job $copyJob2