问题
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