我正在使用System.Management.Automation.Runspaces.Pipleline
创建一个 powershell 管道实例并在 c# 控制台应用程序中执行我的 powershell 脚本,问题是如果脚本最终出现错误,那么我不知道如何在控制台屏幕上打印该错误。
这是我的代码,
System.Management.Automation.Runspaces.Runspace PowershellRunspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowershellRunspace.Open();
System.Management.Automation.RunspacesPipeline PowershellPipeline = PowershellRunspace.CreatePipeline();
PowershellPipeline.Commands.AddScript(PowershellScript);
PowershellPipeline.Commands.AddScript("Out-String");
foreach (string IpAddress in ActiveSystemIPAddresses)
{
PowershellPipeline.Commands.AddScript("Stop-Computer -ComputerName \"" + IpAddress + "\" -Credential $Credentials");
}
try
{
Collection<PSObject> output = PowershellPipeline.Invoke();
if (PowershellPipeline.HadErrors)
{
Console.WriteLine("Cannot shutdown this server IP");
}
PowershellPipeline.Stop();
StringBuilder results = new StringBuilder();
foreach (PSObject obj in output)
{
results.AppendLine(obj.ToString());
}
Console.WriteLine(results);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
PowershellRunspace.Close();
我可以看到该属性Pipeline.HadErrors
,但如果检测到错误,它只会将我拉到循环中,它会做任何事情来获取错误消息。我的问题是如何在控制台屏幕上获取实际错误?