我有 3 个 powershell 命令:
shell.AddScript("Exit-PSSession");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");
现在我不需要前两个的任何响应,但我需要第三个的错误日志。因为我无法预见会发生多少错误,所以我想至少从所有错误消息中清除 shell
,最好是一个完整的空 shell
。
我的解决方案是这样的:
shell.AddScript("Exit-PSSession");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
shell.Invoke();
shell.Streams.ClearStreams();
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");
但不知何故 ClearStreams
什么都不做,shell
仍然知道所有旧错误和之前的两个命令。
Microsoft 方面没有提供更多信息,只是说此方法存在并且应该清除 shell
。 ( Microsoft Help for ClearStreams ) 或 Microsoft Help for streams in general
是我漏掉了什么,还是我误解了他们的意思
(Powershell 是 5.0 版)和 C# 运行 4.6 NET Framework
提前感谢您的帮助。
最佳答案
你可以使用这个:
powershell.Streams.Error();
示例:
PowerShell powershell = PowerShell.Create();
powershell.Runspace = CreateRunSpace.runspace;
var exec = "Set-Mailbox -Identity John -DeliverToMailboxAndForward $true -ForwardingSMTPAddress 'manuel@contoso.com'";
powershell.AddScript(exec);
powershell.Streams.Error.Clear();
powershell.Streams.Warning.Clear();
var result = powershell.Invoke();
MessageBox.Show(powershell.Streams.Error.Count().ToString()+" error counts");
foreach (var errorRecord in powershell.Streams.Error)
{
MessageBox.Show(errorRecord.ToString()+"first - error");
}
请求您发布完整的脚本。什么样的对象 shell 是什么。我认为它会有一个方法,如 .Clear()
注意:我明白了:
sh.Commands.AddScript("Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager"); sh.Invoke(); sh.Commands.Clear();
你能检查一下吗
关于c# - 在 C# 中清除 Powershell 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41462495/