c# - 在 C# 中清除 Powershell 流

标签 c# shell powershell

我有 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/

相关文章:

c# - 用于存储客户特定要求的设计模式

c# - Datagridview 未显示在网页中

c# - 使用内部节点解析 XML?

linux - 使用 shell 脚本替换文件中的标记

powershell - 如何只捕获括号中包含的子字符串?

PowerShell Write-Debug 不会输出数组,但 Write-Output 会。这是故意的吗?

c# - NHibernate 抛出 Session 已关闭

linux - 导出变量,这些变量是 shell 中的变量值

linux - 如何通过比较文件名和文件夹名将文件复制到同名文件夹?

PowerShell 无法确定正在使用的参数集