How Can We Help?
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$code = { param( [string]$Server, [string]$SessionId, [string]$VMName ) Set-PowerCLIConfiguration -DisplayDeprecationWarnings $false -Confirm:$false | Out-Null Connect-VIServer -Server $Server -Session $SessionId Get-VM -Name $VMName } $vmName = 'TestVM' $sJOb = @{ ScriptBlock = $code ArgumentList = $global:DefaultVIServer.Name, $global:DefaultVIServer.SessionId, $vmName } Start-Job @sJob |
Once a job is started in the background, you can wait for its completion and ‘receive’ the output. For example like this.
1 2 3 |
$j = Start-Job @sJob Receive-Job -Job $j -Wait |
Get acquainted with all the Job related cmdlet to use background jobs at their fullest potential.
Peter Titus
Exactly what I needed!
I had almost given up on calling Invoke-VMScript through Start-Job.
Thanks a lot!