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

假装没事ソ 提交于 2019-12-02 05:00:53

问题


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";
        }
    }
}

So my code works up to a point. you click the windows form application button and it will run windows Powershell in 64bit as an administrator but won't run a .ps1 script "c:\path\script.ps1" or the command directly written out like the "sfc /scannow" above.

I was reading that the powershell commands won't work sometimes if the "Set-ExecutionPolicy Unrestricted" isn't loaded somewhere in the beginning of the code.

Please help! I have been looking everywhere for an answer.


回答1:


First of all, you need to specify the Arguments property before you start the process:

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);

Second, you'll need to tell PowerShell that sfc /scannow is a command, and not command line switches.

On the command line you would do powershell.exe -Command "sfc /scannow", so the correct Arguments value in your case would be

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

("" is the escape sequence for " in verbatim string literals)

For .ps1 files, use the -File switch:

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

If you don't know the execution policy on the target system, you can bypass it without affecting the machine-wide policy with -ExecutionPolicy Bypass:

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


来源:https://stackoverflow.com/questions/33509773/run-a-powershell-command-as-an-administrator-commands-themself-wont-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!