我正在从 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/