在 Pipeline.Invoke 抛出后捕获 C# 中的 Powershell 输出
-
22-07-2019 - |
题
我正在从 C# 应用程序运行 Powershell 测试脚本。该脚本可能会因错误的 cmdlet 而失败,从而导致 pipeline.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?
}
解决方案 2
我最终使用的解决方案是实现我们自己的 PSHost 来处理 PowerShell 的输出。这方面的初步信息来自 http://community.bartdesmet.net/blogs/bart/archive/2008/07/06/windows-powershell-through-ironruby-writing-a-custom-pshost.aspx 在“构建自定义 PS 主机”部分。
就我而言,它确实还需要使用自定义 PSHostRawUserInterface。
以下是所做工作的快速概述。我只列出了我实际实现的函数,但有很多只是包含 throw new NotImplementedException();
private class myPSHost : PSHost
{
(Same as what the above link mentions)
}
private class myPSHostUI : PSHostUserInterface
{
private myPSHostRawUI rawui = new myPSHostRawUI();
public override void Write // all variations
public override PSHostRawUserInterface RawUI { get { return rawui; } }
}
private class myPSHostRawUI : PSHostRawUserInterface
{
public override ConsoleColor ForegroundColor
public override ConsoleColor BackgroundColor
public override Size BufferSize
}
其他提示
不知道这是有帮助的。我猜你正在运行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);
}
我也有同样的问题。当 pipeline.Invoke() 抛出异常时获取输出的最简单方法是使用 调用(IEnumerable 输入,IList 输出)
示例展示了如何获取所有输出、错误、减弱等。以正确的顺序
PowerShell 脚本
Write-Output "Hello world"
Write-Error "Some error"
Write-Warning "Some warning"
throw "Some exception"
C#
List<string> RunLog = new List<string>();
using (System.Management.Automation.PowerShell psInstance = System.Management.Automation.PowerShell.Create())
{
psInstance.AddScript(_Script);
psInstance.Streams.Error.DataAdded += (sender, args) =>
{
ErrorRecord err = ((PSDataCollection<ErrorRecord>)sender)[args.Index];
RunLog.Add($"ERROR: {err}");
};
psInstance.Streams.Warning.DataAdded += (sender, args) =>
{
WarningRecord warning = ((PSDataCollection<WarningRecord>)sender)[args.Index];
RunLog.Add($"WARNING: {warning}");
};
... etc ...
var result = new PSDataCollection<PSObject>();
result.DataAdded += (sender, args) =>
{
PSObject output = ((PSDataCollection<PSObject>)sender)[args.Index];
RunLog.Add($"OUTPUT: {output}");
};
try
{
psInstance.Invoke(null, result);
}
catch(Exception ex)
{
RunLog.Add($"EXCEPTION: {ex.Message}");
}
}
不隶属于 StackOverflow