c# - 在 Pipeline.Invoke 抛出后在 C# 中捕获 Powershell 输出

标签 c# powershell powershell-1.0

我正在从 C# 应用程序运行 Powershell 测试脚本。由于错误的 cmdlet 导致 pipe.Invoke() 引发异常,脚本可能会失败。

我能够捕获我需要的有关异常的所有信息,但我希望能够显示脚本到那时为止的输出。我没有任何运气,因为在抛出异常时结果似乎为空。

有什么我想念的吗?谢谢!

m_Runspace = RunspaceFactory.CreateRunspace();
m_Runspace.Open();
Pipeline pipe = m_Runspace.CreatePipeline();
pipe.Commands.AddScript(File.ReadAllText(ScriptFile));
pipe.Commands.Add("Out-String");
try {
   results = pipe.Invoke();
}
catch (System.Exception)
{
   m_Runspace.Close();
   // How can I get to the Powershell output that comes before the exception?
}

最佳答案

不确定这是否有帮助。我猜你正在运行 V1。这种 V2 方法不会抛出并打印结果:

Hello World
67 errors

string script = @"
  'Hello World'
  ps | % {
    $_.name | out-string1
  }
";

PowerShell powerShell = PowerShell.Create();

powerShell.AddScript(script);
var results = powerShell.Invoke();

foreach (var item in results)
{
  Console.WriteLine(item);
}

if (powerShell.Streams.Error.Count > 0)
{
  Console.WriteLine("{0} errors", powerShell.Streams.Error.Count);
}

关于c# - 在 Pipeline.Invoke 抛出后在 C# 中捕获 Powershell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1233640/

相关文章:

c# - Ruby 等效于 C# Linq 聚合方法

powershell - 如何在PowerShell中计算对象数量?

sql - 如何在Powershell中遍历数据表?

azure - 使用 powershell,如何为路径段中版本的 api 管理服务创建 api?

powershell - 如何在 v1.0 中以编程方式从 PowerShell cmdlet 获取警告输出?

sorting - 排序文件的大小是powershell中原始文件的两倍

c# - 如何获取下一个星期日的日期?

c# - 添加 .ToArray 或 .ToList 是否总能使数据库查询更快?

c# - 在标签中显示多行文本框文本之间的空格

powershell - 使用Powershell编辑多个XML文件