Working with PowerShell Jobs

Posted on Updated on

PowerShell Jobs is very effective way to achieve faster, recently I used to work with it and provides big improvements, but it shouldn’t be used in all cases, but only when you need your Script to run in parallel threading

for example, if you you have 1000 files, and you want to run powershell script to process it, you can split your script to run for 100 file per job, and this will optimize running time by over 80%

but still PowerShell jobs is a bit tricky in executing and debugging, in this post will summarize what you really want to use PowerShell Jobs efficiently

for($i =0; $i -lt 5; $i++)
{
$job=Start-Job -Name "Job-$i" -ScriptBlock {
    Start-Sleep -s 5
    $x = 10
    $z = $x + 5
    (Get-Random -Minimum 1 -Maximum 1000).ToString()   >> "C:\temp\file.txt"
   }
}

Debug-Job -Job $job;

Debugging process is also tricky, you should be aware of few things

  • The .ps1 file must be saved before debugging
  • Write-host will not work in the job, instead use Out-file to write in a log file
  • Put break point on the Debug-Job line
  • If the job ends quickly then debug will not work, make the function run for longer, by adding “start-sleep -s 5” in the job it self, like in the above example

If you want to bypass a parameter to the Job, you can do this in many ways

  1. Pass parameter directly to the job, using $input method, like the below (Please make sure to use $input word (case sensitive), otherwise it will not work
for($i =0; $i -lt 5; $i++)
{
$job=Start-Job -Name "Job-$i" -InputObject $i -ScriptBlock {
    Start-Sleep -s 10
    $z = $input
    $input   >> "C:\temp\file.txt"
   }
}

Debug-Job -Job $job;

2. The job only takes one single input, you can send array of string as object in this input, and process it in the job

3. you can write your input in a file, and then the job read it

In general I prefer to use file with jobs, it is easier in handling like the below

for($i =0; $i -lt 5; $i++)
{
$job=Start-Job -Name "Job-$i" -InputObject $i -ScriptBlock {
    Start-Sleep -s 5
    C:\Temp\otherscript.ps1 -param1 $input

   }
}

Please leave me a comment if you face any issues with the Jobs

Regards

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s