PowerShell is single-threaded and can only do one thing at a time. Background jobs can add additional PowerShell processes to processing jobs in the background. It is a good solution when the program needs to run at the same time and the amount of data is not very large. But returning data back from PowerShell is a very cumbersome task, and it will waste a lot of time. Will cause the script to be slower.
Here are 3 concurrent execution tasks:
Copy Code code as follows:
$start = Get-date
# Get all Hotfixes
$task 1 = {Get-hotfix}
# Get all scripts in your profile
$task 2 = {Get-service | Where-object Status-eq Running}
# Parse log file
$task 3 = {Get-content-path $env: Windir\windowsupdate.log | Where-object {$_-like ' *successfully installed* '}}
# run 2 tasks in the background, and 1 in the foreground task
$job 1 = start-job-scriptblock $task 1
$job 2 = Start-job-scriptblock $task 2
$result 3 = Invoke-command-scriptblock $task 3
# Wait for the remaining tasks to complete (if does not do yet)
$null = wait-job-job $job 1, $job 2
# Now they are do, get the results
$result 1 = receive-job-job $job 1
$result 2 = receive-job-job $job 2
# Discard the jobs
Remove-job-job $job 1, $job 2
$end = Get-date
Write-host-foregroundcolor Red ($end-$start). TotalSeconds
It takes 5.9 seconds to perform all of the tasks above. The results of the three missions will be deposited in $RESULT1, $result 2, and $result 3.
Let's continue to see how long it takes to finish the command at the front desk:
Copy Code code as follows:
$start = Get-date
# Get all Hotfixes
$task 1 = {Get-hotfix}
# Get all scripts in your profile
$task 2 = {Get-service | Where-object Status-eq Running}
# Parse log file
$task 3 = {Get-content-path $env: Windir\windowsupdate.log | Where-object {$_-like ' *successfully installed* '}}
# run them all in the foreground:
$result 1 = invoke-command-scriptblock $task 1
$result 2 = Invoke-command-scriptblock $task 2
$result 3 = Invoke-command-scriptblock $task 3
$end = Get-date
Write-host-foregroundcolor Red ($end-$start). TotalSeconds
As a result, this time it took only 5.05 seconds. and background jobs are done almost at the same time, so background jobs are more appropriate for long-running tasks. The benefit of the data returned from three tasks is that the data available in the foreground can reduce the overhead of the execution process.