我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;
}
}
}