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

前端 未结 1 444
迷失自我
迷失自我 2021-01-22 19:27
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.         


        
相关标签:
1条回答
  • 2021-01-22 20:17

    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""";
    
    0 讨论(0)
提交回复
热议问题