Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

.net - PowerShell host->Process event not raised

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)
question from:https://stackoverflow.com/questions/65853599/powershell-host-process-event-not-raised

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...