The Invoke method used with each of the following examples executes the code immediately and synchronously. The BeginInvoke method is used to execute asynchronously, that is, without waiting for the last operation to complete.
Both the PowerShell instance object and the IASyncResult returned by BeginInvoke must be captured. Assigning the values allows continued access to the instances and is required to retrieve output from the commands:
$psInstance = [PowerShell]::Create().AddCommand('Start-Sleep').AddParameter('Seconds', 300)
$asyncResult = $psInstance.BeginInvoke()
While the job is running, the InvocationStateInfo property of the PowerShell object will show as Running:
PS> $psInstance.InvocationStateInfo
State Reason
----- ------
Running
This state is reflected on the IASyncResult object held in the $asyncResult variable:
PS> $asyncResult
CompletedSynchronously IsCompleted AsyncState AsyncWaitHandle
---------------------- ----------- ---------- ---------------
False False System.Threading.ManualResetEvent
When the command completes, both objects will reflect that state:
PS> $psInstance.InvocationStateInfo.State
Completed
PS> $asyncResult.IsCompleted
True
Setting either (or both) of these variables to null does not stop the script executing in the PowerShell instance. Doing so only removes the variables assigned, making it impossible to interact with the Runspace:
$psInstance = [PowerShell]::Create().AddScript('
1..60 | ForEach-Object {
Add-Content -Path c: empoutput.txt -Value $_
Start-Sleep -Seconds 1
}
')
$asyncResult = $psInstance.BeginInvoke()
$psInstance = $null
$asyncResult = $null
The script continues to execute, filling the output file. The following file may be using Get-Content:
Get-Content c: empoutput.txt -Wait
If the work of the script is no longer required, the Stop method should be called instead of setting variables to null:
$psInstance = [PowerShell]::Create()
$psInstance.AddCommand('Start-Sleep').AddParameter('Seconds', 120)
$psInstance.Stop()
A terminating error is raised when the Stop method is called. If the output from the instance is retrieved using the EndInvoke method, a The pipeline has been stopped error message will be displayed.