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
财产before你开始这个过程:
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);
其次,您需要告诉 PowerShellsfc /scannow
是一个命令,而不是命令行开关。
在命令行上你会做powershell.exe -Command "sfc /scannow"
,所以正确的Arguments
你的情况的价值是
newProcessInfo.Arguments = @"-Command ""sfc /scannow""";
(""
是转义序列"
以逐字字符串文字形式)
For .ps1
文件,使用-File
switch:
newProcessInfo.Arguments = @"-File ""C:\my\script.ps1""";
如果您不知道目标系统上的执行策略,则可以绕过它而不影响机器范围的策略:-ExecutionPolicy Bypass
:
newProcessInfo.Arguments = @"–ExecutionPolicy Bypass -File ""C:\my\script.ps1""";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)