How Can We Help?
< Back
You are here:
Print

Running a background job

PowerShell has a nifty feature that allows you to run code in the background. This is done through the Start-Job cmdlet.

When you want to run PowerCLI code in the background, there are a number of conditions to take care of.

  • Your existing connection to a vSphere Server (vCenter or ESXi) is not inherited by the background job. You will have to establish the connection in the background job. With the SessionId parameter, you can reuse an existing connection.
  • A background job shouldn’t rely on any interactivity. For that reason you want to disable all warning messages any of the PowerCLI cmdlets might generate
  • A background job normally has no access to the variables defined in the calling code. You can pass values through the ArgumentList parameter on the Start-Job cmdlet.
  • You do not need to include any Import-Module cmdlets in your background job., when
    • you are using a PowerShell version (v3 and above) that supports the module autoloading feature
    • you have the PowerCLI modules installed in one of the folders listed in $env:PSMOdulePath,
    • you haven’t used the $PSModuleAutoLoadingPreference variable to change the default behaviour

The following is a minimal example of such a background job. It will call the Get-VM cmdlet for a specific VM’s name.

Once a job is started in the background, you can wait for its completion and ‘receive’ the output. For example like this.

Get acquainted with all the Job related cmdlet to use background jobs at their fullest potential.

One Comment

    Peter Titus

    Exactly what I needed!
    I had almost given up on calling Invoke-VMScript through Start-Job.

    Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Table of Contents