2017-08-10 194 views
1

我有一個PowerShell腳本,我想從EXE觸發。從C#代碼觸發PS1文件。 C#代碼必須包裝在exe

事情已經嘗試過或不能做什麼:

  • 不能運行PowerShell的直接原因進程中運行它期待一個exe文件,而不是一個PowerShell。
  • Powershell腳本非常複雜,因此將它移植到C#中並不是微不足道的,而且會非常耗時。
  • PS2EXE有效,但由於安全策略而無法使用。
  • 試圖谷歌關於如何爲ps1文件創建一個exe文件,但找不到任何解決方案(ps2exe除外)。所以我決定嘗試使用C#執行ps1,然後創建一個exe文件。然後在同一個msi中包裝exe和powershell。

試圖通過簡單地創建過程,並啓動它:

 Process p = new Process(); 
     p.StartInfo = new ProcessStartInfo("powershell.exe"); 
     p.StartInfo.Arguments = @"-Executionpolicy unrestricted C:\script\ms.ps1"; 
     p.StartInfo.CreateNoWindow = true; 
     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     p.Start(); 

上面的代碼工作,但它是閃爍CMD窗口一毫秒左右。

嘗試下面的代碼從源:如上述https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

 string scriptText = System.IO.File.ReadAllText(@"C:\script\ms.ps1"); 
     Runspace runspace = RunspaceFactory.CreateRunspace(); 
     runspace.Open(); 
     Pipeline pipeline = runspace.CreatePipeline(); 
     pipeline.Commands.AddScript(scriptText); 

     pipeline.Commands.Add("Out-String"); 

     pipeline.Invoke(); 
     runspace.Close(); 

同樣的問題,閃爍幾秒鐘黑窗口。

回答以下任何問題都可以解決我的問題嗎?

  1. 如何在不使用PS2EXE的情況下爲powershell創建exe文件?
  2. 從C#代碼調用powershell時,如何禁用Windows彈出窗口?
  3. 有沒有其他辦法可以解決我的問題?

- 感謝

+0

你試過[CreateNoWindow](https://stackoverflow.com/questions/3497924/console-window-still-popping-up-even-after-processwindowstyle-隱)? – Martheen

+0

在調用PowerShell時將-windowstyle添加到您的參數中。 –

+1

什麼樣的安全策略允許運行家庭釀造的C#應用​​程序,但不能運行Ps2Exe應用程序? – vonPryz

回答

0

您好!您可以在項目屬性的控制檯,而不是 選擇「Windows應用程序」 enter image description here

也許它幫助你爲這個:/閃爍着黑色CMD窗口/

您也可以運行內部消除運行腳本命令(像這樣 ):

string MyCommand = "-Command &{ if (!(Test-Path 'c:\\test')) {md 'c:\\test'; get-process | Out-File c:\\test\\MyFile.txt}}"; 

      ProcessStartInfo MyProcInfo = new ProcessStartInfo(); 


      MyProcInfo.FileName = "powershell.exe"; 
      MyProcInfo.Arguments = MyCommand; 

      Process MyProcess = new Process(); 
      MyProcess.StartInfo = MyProcInfo; 
      MyProcess.Start(); 
      MyProcess.WaitForExit();