PowerShell host->Process event not raised

Viewed 66

A sample script looks like this:

Begin
{
    Write-Output "Begin block processed."
}

Process
{
    Write-Output "Process block processed."
}

End
{
    Write-Output "End block processed."
}

When running this through System.Automation.PowerShell host in .NET the output is only:

Begin blocked processed.
End blocked processed.

Any idea why the Process block is not processed.

Basically, the code behind is:

Dim ps As PowerShell = PowerShell.Create()
ps.AddScript(strScriptText)
ps.Invoke(Nothing, outputCollection)

UPDATE: The issue has been fixed. The problem was the order of things.

This order does work:

    AddHandler outputCollection.DataAdded, AddressOf OutputDataReceived
    AddHandler ps.Streams.Error.DataAdded, AddressOf ErrorDataReceived
    AddHandler ps.InvocationStateChanged, AddressOf InvocationStateChanged

    ps.AddScript(strScript)

    ps.AddCommand("Out-String").AddParameter("Stream")

    ps.Invoke(Nothing, outputCollection)

This order does not work:

    AddHandler outputCollection.DataAdded, AddressOf OutputDataReceived
    AddHandler ps.Streams.Error.DataAdded, AddressOf ErrorDataReceived
    AddHandler ps.InvocationStateChanged, AddressOf InvocationStateChanged

    ps.AddCommand("Out-String").AddParameter("Stream")

    ps.AddScript(strScript)

    ps.Invoke(Nothing, outputCollection)
1 Answers

According to Microsoft Documentation:

Within a pipeline, the Process block executes once for each input object that reaches the function.

In your code, you send Nothing as the input object. In visual basic, this is the equivalent of sending an empty IEnumerable object. Since the IEnumerable object is empty, there are no items for the process block to process. Therefore, the process block is not executed, whereas the Begin and End blocks are always executed once no matter how many items are processed.

If you send an IEnumerable object such as a List<> with a single item inside instead of the Nothing keyword, your process block will execute once. Try it.

Related