【问题标题】:PowerShell host->Process event not raisedPowerShell 主机-> 未引发进程事件
【发布时间】:2021-01-22 22:31:07
【问题描述】:

示例脚本如下所示:

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

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

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

在 .NET 中通过 System.Automation.PowerShell 主机运行时,输出仅为:

Begin blocked processed.
End blocked processed.

知道为什么进程块没有处理

基本上,后面的代码是:

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

更新:问题已得到解决。问题在于事情的顺序。

这个命令确实有效:

    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)

此命令无效:

    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)

【问题讨论】:

  • 无法重现...我看到所有三个输出

标签: .net vb.net powershell


【解决方案1】:

根据Microsoft Documentation

在管道中,Process 块对到达函数的每个输入对象执行一次。

在您的代码中,您发送Nothing 作为输入对象。在 Visual Basic 中,这相当于发送一个空的 IEnumerable 对象。由于 IEnumerable 对象为空,因此进程块没有要处理的项目。因此,进程块不被执行,而Begin和End块无论处理多少项总是执行一次。

如果您发送 IEnumerable 对象,例如 List<>,其中包含单个项目而不是 Nothing 关键字,则您的进程块将执行一次。试试看。

【讨论】:

  • 谢谢,但不是这样。我更新了原帖。造成问题的是 AddScript / AddCommand 的顺序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 2011-06-05
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多