The EndInvoke method and the PSDataCollection object

EndInvoke is one of two possible ways to get output from a PowerShell instance. The EndInvoke method may be called as follows:

$psInstance = [PowerShell]::Create()
$asyncResult = $psInstance.AddScript('1..10').BeginInvoke()
$psInstance.EndInvoke($asyncResult)

If the invocation has not finished, EndInvoke will block execution until it has completed.

The second possible method involves passing a PSDataCollection object to the BeginInvoke method:

$instanceInput = [System.Management.Automation.PSDataCollection[PSObject]]::new()
$instanceOutput = [System.Management.Automation.PSDataCollection[PSObject]]::new()

$psInstance = [PowerShell]::Create()
$asyncResult = $psInstance.AddScript('
1..10 | ForEach-Object {
Start-Sleep -Seconds 1
$_
}
').BeginInvoke(
$instanceInput,
$instanceOutput
)

The $psInstance and $asyncResult variables are still used to determine whether the script has completed. Results are available in $instanceOutput as they become available. Attempting to access $instanceOutput in the console will block execution until the script completes. New values added to the collection will be displayed as they are added.

The unused $instanceInput variable in the preceding example may be populated with values for an input pipeline if required, for example:

$instanceInput = [System.Management.Automation.PSDataCollection[PSObject]](1..10)
$instanceOutput = [System.Management.Automation.PSDataCollection[PSObject]]::new()

$psInstance = [PowerShell]::Create()
$asyncResult = $psInstance.AddCommand('ForEach-Object').AddParameter('Process', { $_ }).BeginInvoke(
$instanceInput,
$instanceOutput
)

The AddCommand method was used in the preceding example as ForEach-Object will act on an input pipeline. A script can accept pipeline input within a process block; pipeline input is not implicitly passed to the commands within the script. The following example implements an input pipeline and uses the built-in $_ variable to repeat the numbers from the input pipeline:

$instanceInput = [System.Management.Automation.PSDataCollection[PSObject]](1..10)
$instanceOutput = [System.Management.Automation.PSDataCollection[PSObject]]::new()

$asyncResult = $psInstance.AddScript('

process {
$_
)
').BeginInvoke(
$instanceInput,
$instanceOutput
)

Each of the examples so far has concerned itself with running a single script or a set of commands.

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

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