2015-11-03 106 views
2
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Diagnostics; 


namespace WindowsFormsApplication 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      var newProcessInfo = new System.Diagnostics.ProcessStartInfo(); 
      newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"; 
      newProcessInfo.Verb = "runas"; 
      System.Diagnostics.Process.Start(newProcessInfo); 
      newProcessInfo.Arguments = @"sfc /scannow"; 
     } 
    } 
} 

所以我的代碼工作到一定程度。您單擊Windows窗體應用程序按鈕,它將以管理員身份運行64位Windows Powershell,但不會運行.ps1腳本「c:\ path \ script.ps1」或直接寫出「sfc/scannow」命令以上。以管理員身份運行PowerShell命令 - 命令本身不會加載

我讀到,如果「Set-ExecutionPolicy Unrestricted」沒有加載到代碼開頭的某處,powershell命令有時不起作用。

請幫忙!我一直在尋找答案。

+0

'[...] \ Syswow64資料\ [...] \ powershell.exe'是* 32位* powershell –

+0

爲什麼不運行沒有PowerShell的命令? –

+0

這只是一個例子。實際上,我將使用Powershell命令進行一些編程。那麼哪個文件夾是64位的PowerShell,如果這是不正確的。 SysWOW64應該是Windows系統的所有64位版本。 – DDJ

回答

1

首先,你需要之前指定Arguments屬性啓動過程:

var newProcessInfo = new System.Diagnostics.ProcessStartInfo(); 
newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"; 
newProcessInfo.Verb = "runas"; 
newProcessInfo.Arguments = @"sfc /scannow"; 
System.Diagnostics.Process.Start(newProcessInfo); 

其次,你需要告訴PowerShell會在sfc /scannow是一個命令,而不是命令行開關。

在命令行中,你會做powershell.exe -Command "sfc /scannow",所以你的情況正確Arguments值是

newProcessInfo.Arguments = @"-Command ""sfc /scannow"""; 

""是逐字字符串爲"轉義序列)

對於.ps1文件,使用-File開關:

newProcessInfo.Arguments = @"-File ""C:\my\script.ps1"""; 

如果你不知道目標系統上的執行策略,你可以繞過它,而不會影響與-ExecutionPolicy Bypass機器寬政策:

newProcessInfo.Arguments = @"–ExecutionPolicy Bypass -File ""C:\my\script.ps1"""; 
+0

謝謝你的所有知識!這真的幫助了我。 :) – DDJ

相關問題