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

标签 c# powershell administrator

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”多于。

我读到如果“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""";

关于c# - 以管理员身份运行 Powershell 命令 - 命令本身不会加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509773/

相关文章:

powershell - 从 MSdeploy runco​​mmand 运行 PowerShell 不会退出

database - 在 Oracle 中跟踪失败的用户连接

azure - 使用其他属性获取扩展属性

c# - 紧凑框架: Update of label in thread not working

c# - Excel 数据读取器问题、列名称和工作表选择

c# - LoaderOptimizationAttribute 的作用

powershell - 信任关系丢失时如何重新加入域

security - 将 "Network Service"帐户添加到管理员组

asp.net 使用管理员帐户运行程序

c# - 如何从 .NET 应用程序连接到 SQL Server Compact?