The Start-Job, Get-Job, and Remove-Job commands

The Start-Job command is most commonly used to execute a script block in a very similar manner to Invoke-Command. Start-Job may also be used to execute a script using the FilePath parameter.

When Start-Job is executed, a job object, System.Management.Automation.PSRemotingJob is created. The job object continues to be available using the Get-Job command regardless of whether the output from Start-Job is assigned. This is shown as follows:

PS> Start-Job -ScriptBlock { Start-Sleep -Seconds 10 }

Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 Job1 BackgroundJob Running True localhost Start-Sleep -Seconds 10

PS> Get-Job

Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 Job1 BackgroundJob Running True localhost Start-Sleep -Seconds 10

When a script is using jobs, the common practice is to capture the jobs created instead of relying entirely on Get-Job. This avoids problems if module used in a script also creates jobs. The state of the job is reflected on the job object; Get-Job is not required to update the status.

Job objects and any data the job has returned remain available until they are removed using the Remove-Job command.

Start-Job includes a RunAs32 parameter to run code under the 32-bit version of PowerShell if required.

The InitializationScript parameter of Start-Job may be used to isolate setup steps, such as importing modules, creating functions, and setting up variables. Each job executes in a separate thread, which means that values cannot be automatically shared.

Start-Job does not offer a throttling capability. PowerShell will simultaneously execute every job. Each job will compete for system resources. A while or do loop may be implemented to maintain a pool of running jobs:

$listOfJobs = 1..50
foreach ($job in $listOfJobs) {
while (@(Get-Job -State Running).Count -gt 10) {
Start-Sleep -Seconds 10
}
Start-Job { Start-Sleep -Seconds (Get-Random -Minimum 10 -Maximum 121) }
}

The jobs created here do not return any data and can therefore be removed as soon as they have completed. Data must be retrieved from a job before is it removed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.152