Tuesday, June 20, 2017

Executing Parallel tasks in Power-Shell……………

There can be situation in PowerShell when we want to execute multiple blocks of code in parallel , wait for the block to complete execution and then proceed further executing rest code. This can be done in PowerShell using the command Start-Job  and Wait-Job

Below code block will show how you can accomplish the same. We can ask PowerShell to execute a code block in parallel using the Start-Job commandlet. The Start-Job commandlet  accepts the code block to be executed in parallel as value for -ScriptBlock  and the parameters to the block can be passed as values for - ArgumentList

This code tries to write lines to a common files stored at d:\Wait-Job_Test_Log.txt from two jobs Job1 and Job2

clear

$name = "Rajesh"
$name2 = "Renjith"
 
#Starting Job1 and passing $name,$name2 as arguments to Script block
Start-Job -Name Job1 -ArgumentList $name,$name2 -ScriptBlock {

  param ($name1,$name2)

  #Just adding some delay

  Start-Sleep -s 10

  #Add content to file

  Add-Content -Value "Job1 Started....." -Path "d:\Wait-Job_Test_Log.txt"

  #Add content to file

  Add-Content -Value "Hello $name1 I am from Job1" -Path "d:\Wait-Job_Test_Log.txt"

  #Add content to file

  Add-Content -Value "Hello $name2 I am from Job1"-Path "d:\Wait-Job_Test_Log.txt"
}

#Starting Job2
Start-Job -Name Job2 -ScriptBlock {

  #Just adding some delay

  Start-Sleep -s 20

  #Add content to file

  Add-Content -Value "Job2 Started....." -Path "d:\Wait-Job_Test_Log.txt"

  #Add content to file

  Add-Content -Value "I am From Job2" -Path "d:\Wait-Job_Test_Log.txt"
}

#Add content to file
Add-Content -Value "I am from Outside, waiting for job1,job2 to finish" -Path "d:\Wait-Job_Test_Log.txt"


#Check if a Job with name Job1 has already been started,

if([bool](get-job -Name Job1 -ea silentlycontinue) )
{

  #if Yes, wait for the jon completed
  Wait-Job Job1

  #Add content to file
  Add-Content -Value "Job1 Finished....." -Path "d:\Wait-Job_Test_Log.txt"
}

#Check if a Job with name Job1 has already been started,
if([bool](get-job -Name Job2 -ea silentlycontinue) )
{

  #if Yes, wait for the jon completed
  Wait-Job Job2

  #Add content to file
  Add-Content -Value "Job2 Finished....." -Path "d:\Wait-Job_Test_Log.txt"
}

#Add content to file
Add-Content -Value "I am from Outside after Jobs completed" -Path "d:\Wait-Job_Test_Log.txt"
 
#Add content to file

Add-Content -Value "I am from Outside after Jobs completed" -Path "d:\Wait-Job_Test_Log.txt"

No comments:

Post a Comment