2012-10-15 22 views
12

我正在使用System.Management.Automation.Runspaces來執行PowerShell腳本。 有沒有一個選項可以讀取給定腳本的退出代碼?如何通過c#讀取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; 
     } 
    } 
} 

回答

5

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 . . . 
0

這就像問價值給你剛剛創建的運行空間一樣簡單:

s_ps.AddScript("$LASTEXITCODE"); 
results = s_ps.Invoke(); 
int.TryParse(results[0].ToString(),out valorSortida);