以管理员身份运行PowerShell命令 - 命令本身不会加载

问题描述:

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

首先,你需要之前指定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