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
- $source = "\\RemoteServer\c$\fileshares"
- $target = "D:\CopyTest"
- Copy-Item -Path $source -Destination $target -Recurse Verbose
Async operation
- As a next step, we will wrap up this in a Start-Job
- $copyJob = Start-Job –ScriptBlock {
- $source = "\\RemoteServer\c$\fileshares"
- $target = "D:\CopyTest"
- Copy-Item -Path $source -Destination $target -Recurse Verbose
- }
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.
Real time example
To carry out multiple copy operations asynchronously:
- $copyJob1 = Start - Job– ScriptBlock
- {
- $source = "\\RemoteServer\c$\fileshares"
- $target = "D:\CopyTest"
- Copy - Item - Path $source - Destination $target - Recurse Verbose
- }#
- Code here will run async
- $copyJob2 = Start - Job– ScriptBlock
- {
- $source = "\\RemoteServer\c$\Shared"
- $target = "D:\CopyTest"
- Copy - Item - Path $source - Destination $target - Recurse Verbose
- }#
- Code here will run async
- Wait - Job $copyJob1
- Wait - Job $copyJob2