PowerShell performs tasks in parallel

Source: Internet
Author: User

In PowerShell, you can easily perform background tasks and have multiple background tasks run in parallel. This article describes some of the job-related commands in PowerShell and demonstrates how to perform multiple tasks concurrently in the background by using the demo.

mode for performing background tasks in PowerShell

Describes the process model for performing background tasks in PowerShell (this figure is from the Internet):

First we need a PowerShell process to perform commands that interact with the user, such as executing the start-job command to run a background task. Each of these background tasks is executed in a newly started PowerShell process. So, if we start three background tasks at the same time, a total of four PowerShell processes are running at the same time.

Job-related commands

The start-job command initiates a task that runs in the background. Note that every task that runs through the start-job command creates a separate PowerShell process.

The stop-job command is used to stop a running background task (a task initiated by Start-job).

The get-job command is used to obtain the background Task object in the current session.

The wait-job command blocks the current execution process and waits for the specified background task execution to finish.

The receive-job command is used to obtain the execution results of the background execution task. For example, at the end of a background task, you can get the result by receive-job and output when the task executes.

The remove-job command deletes the completed task in the current session. When a task is finished, it is not automatically deleted unless you call the remove-job command to delete it, or you can close the session. If you use Remove-job to delete a running task, the command runs unsuccessfully. You need to use the Stop-job command to stop the task first and then delete it with Remove-job.

perform tasks in the background

If you just start a task that executes in the background, don't need to know the result of the task execution, and don't care when the task is finished, just start the execution of the task with the Start-job command:

> Start-job-scriptblock {Sleep 5}
start a single task and wait for the task to end

In most cases we need to know the end time of the task, which can be blocked by the wait-job command until the waiting task ends:

" Hello World. "; } | Wait-job

Note that the above content is output by the Wait-job command, when the status of the task is "completed".

Further, we also want to get the output from the task execution process. Then we need to use the Receive-job command. You can execute the receive-job command at any time after the task is started, but if you want to get the full output, you need to call it at the end of the task and use it with the Wait-job command:

$job " Hello World. " ; } Wait$jobReceive$job

Save the above code in the file Mytask.ps1 to execute:

The receive-job command outputs the output of the task we performed in the background.

perform multiple tasks in the background and wait for the end

Because the Start-job command is non-blocking, theoretically we can execute any number of times to start a lot of background tasks. And waiting for a single task, you can still use the wait-job command to wait for all tasks to end, but you'll need to work with the Get-job command at this point:

> Get-job | Wait-job

The more common way is that we constantly check the state of the task in the while loop, and when all of the tasks are "completed", the end of all Tasks execution:

Remove-job *#Test Timing starts$start _time= (get-Date) Start-job-scriptblock {sleep 9; Write-host"Hello myJob1."; }-name"MyJob1"Start-job-scriptblock {sleep 5; Write-host"Hello myJob2."; }-name"MyJob2"$taskCount= 2 while($taskCount -GT0){    foreach($job inchget-Job) {        $state= [string]$job. Stateif($state -eq "completed") {Write-host ($job. Name +"has been completed") Receive-job$job            $taskCount--Remove-job$job}} Sleep1}"All tasks are complete" #Get The task running time(New-timespan$start _time). totalseconds

Save the above code in the Mytask.ps1 file and execute:

In the code, we name each task and constantly use the Get-job command in the while loop to check the current state of the task, and if the status of the task is found to be "completed", it is removed by the Remove-job command and the name and output of the task are printed before deletion.

encapsulates a function that performs a background task

Here we encapsulate a simple function to perform multiple tasks in parallel:

functionrun-tasks{Param    (        $TASKARR,        $parallelcount=1    )    #Test Timing starts    $startTime= (get-Date)#Remove all background tasks already in this sessionRemove-job *#use variable $taskCount Save the number of tasks that have not yet completed    $taskCount=$TASKARR. Length#determine if the number of parallel tasks set exceeds the number of tasks in the current task queue    if($parallelCount -GT $TASKARR. Length) {$parallelCount=$TASKARR. Length}#start the initial task    foreach($i inch1..$parallelCount) {Start-job$TASKARR[$i-1]-name"task$i"    }    #tasks that start after the initial task is completed    $nextIndex=$parallelCount        #keep polling for established tasks when there are tasks in the task queue, and delete this task when a background task ends    #The next task is then fetched from the task queue for execution, and then waits for all tasks to complete.      while(($nextIndex -lt $TASKARR. Length)-or($taskCount -GT0))    {        foreach($job inchget-Job) {            $state= [string]$job. Stateif($state -eq "completed") {Write-host ($job. Name +"has been completed with the following results:") Receive-job$jobRemove-job$job                $taskCount--if($nextIndex -lt $TASKARR. Length) {$taskNumber=$nextIndex+ 1Start-job$TASKARR[$nextIndex]-name"Task$tasknumber"                    $nextIndex++}}} sleep1    }        "All tasks are complete"    #Get The task running time(New-timespan$startTime). TotalSeconds}

The above function executes the user's task in the background and waits for all of the task execution to finish. And the user can specify the number of simultaneous tasks to be performed, outputting the output of the task after the task is completed. Next, let's try using this function to perform some tasks:

#Define 6 Tasks$task 1= {Sleep 12; Write-host"Hello myJob1."; }$task 2= {Sleep 5; Write-host"Hello myJob2."; }$task 3= {Sleep 8; Write-host"Hello myJob3."; }$task 4= {Sleep 3; Write-host"Hello myJob4."; }$task 5= {sleep 20; Write-host"Hello myJob5."; }$task 6= {Sleep 15; Write-host"Hello myJob6."; } #writes 6 tasks to an array as a task queue$TASKARR=$task 1,$task 2,$task 3,$task 4,$task 5,$task 6#run the tasks in the array to allow 4 tasks to run concurrentlyRun-tasks-taskarr$TASKARR-parallelcount 4

Here is the result of the run:

Summary

It's a great thing to be able to perform tasks in the background as you like! Of course, you can do things fast and well for work (and not to say). This article just provides a simple demo of running parallel tasks, omitting the important things like exception handling, but this is enough for you to start the PowerShell parallel task tour.

Reference:
Windows PowerShell Combat Second Edition
Powershell: Simple script to implement parallel tasks

PowerShell performs tasks in parallel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.