gpt4 book ai didi

c# - 如何通过 C# 读取 PowerShell 退出代码

转载 作者:可可西里 更新时间:2023-11-01 08:11:32 25 4
gpt4 key购买 nike

我正在使用 System.Management.Automation.Runspaces 来执行 PowerShell 脚本。有没有我可以读取给定脚本的退出代码的选项?

using System.IO;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace PowerShell
{
public class PowerShellExecuter
{
public Collection<PSObject> RunPsScript(string psScriptFile)
{
string psScript;
if (File.Exists(psScriptFile))
{
psScript = File.ReadAllText(psScriptFile);
}
else
{
throw new FileNotFoundException("Wrong path for the script file");
}
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();

RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

Pipeline pipeLine = runSpace.CreatePipeline();
pipeLine.Commands.AddScript(psScript);
pipeLine.Commands.Add("Out-String");

Collection<PSObject> returnObjects = pipeLine.Invoke();
runSpace.Close();

return returnObjects;
}
}
}

最佳答案

PowerShell 命令具有比整数退出代码更丰富的错误机制。存在非终止错误出现的错误流。终止错误会导致抛出异常,因此您需要处理这些异常。下面的代码展示了如何使用这两种机制:

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace PowerShellRunspaceErrors
{
class Program
{
private static PowerShell s_ps;

static void Main(string[] args)
{
s_ps = PowerShell.Create();
ExecuteScript(@"Get-ChildItem c:\xyzzy");
ExecuteScript("throw 'Oops, I did it again.'");
}

static void ExecuteScript(string script)
{
try
{
s_ps.AddScript(script);
Collection<PSObject> results = s_ps.Invoke();
Console.WriteLine("Output:");
foreach (var psObject in results)
{
Console.WriteLine(psObject);
}
Console.WriteLine("Non-terminating errors:");
foreach (ErrorRecord err in s_ps.Streams.Error)
{
Console.WriteLine(err.ToString());
}
}
catch (RuntimeException ex)
{
Console.WriteLine("Terminating error:");
Console.WriteLine(ex.Message);
}
}
}
}

如果你运行这个程序,它会输出:

Output:
Non-terminating errors:
Cannot find path 'C:\xyzzy' because it does not exist.
Terminating error:
Oops, I did it again.
Press any key to continue . . .

关于c# - 如何通过 C# 读取 PowerShell 退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12895503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com