简体   繁体   English

C# PowerShell 在使用 AddCommand 时不捕获 PowerShell.Streams,但在使用 AddScript 时捕获

[英]C# PowerShell does not capture PowerShell.Streams when using AddCommand but does when using AddScript

I am encountering a very strange behavior when using PowerShell in C#.在 C# 中使用 PowerShell 时,我遇到了一个非常奇怪的行为。 When I execute当我执行

InitialSessionState s = InitialSessionState.CreateDefault2();
var ps = PowerShell.Create(s);


ps.AddCommand("Write-Information")
    .AddArgument("<test>")
    .Invoke();

// Writes 0. But why?
Console.WriteLine(PS.Streams.Information.Count);

no streams (Stream.Information, Stream.Error, ...) are captured.没有流(Stream.Information, Stream.Error, ...)被捕获。 But when I use但是当我使用

ps.AddScript("Write-Information '<test>'")
    .Invoke();

// Writes 1 as expected
Console.WriteLine(PS.Streams.Information.Count);

Everything works as expected.一切都按预期工作。 Can anybody explain this difference?任何人都可以解释这种差异吗? Am I missing some conceptions?我错过了一些概念吗? How can there be a difference?怎么可能有区别? How can I capture the streams of a AddCommand invocation?如何捕获 AddCommand 调用的流?

Thanks for any input on this!感谢您对此的任何意见!

Sorry for the confusion, it was my bad.很抱歉造成混乱,这是我的错。 I was calling ps.AddCommand("...").InvokeAsync() multiple times on the same PowerShell instance, which meant that only the first command was executed and the second command was not executed at all (and hence no Stream data).我在同一个 PowerShell 实例上多次调用ps.AddCommand("...").InvokeAsync() ,这意味着只执行了第一个命令,根本没有执行第二个命令(因此没有流数据) .

Is the correct (and best practice) to create a new PowerShell instance (with same runspace) for every command I want to invoke separately?为我想单独调用的每个命令创建一个新的 PowerShell 实例(具有相同的运行空间)是否正确(和最佳实践)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM