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

Run a Powershell command as an Administrator - Commands themself won't load

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 表单应用程序按钮,它将 运行 windows 64 位的 Powershell 作为管理员,但不会 运行 .ps1 脚本 "c:\path\script.ps1" 或者像上面的 "sfc /scannow" 这样直接写出来的命令。

我读到如果 "Set-ExecutionPolicy Unrestricted" 没有加载到代码开头的某处,Powershell 命令有时会不起作用。

请帮忙!我一直在到处寻找答案。

首先,您需要在启动进程之前指定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""";