如何使用多个命令和 Set-ExecutionPolicy Unrestricted -force 创建一个 .ps1 文件?

How to make a .ps1 file with multiple commands and Set-ExecutionPolicy Unrestricted -force?

var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
newProcessInfo.Arguments = @"-executionpolicy unrestricted -Command ""C:\Windows\system32\sfc.exe /scannow""";


/*
newProcessInfo.Arguments = @"-Command ""sfc /scannow""";
newProcessInfo.Arguments = @"-File ""C:\my\script.ps1""";
newProcessInfo.Arguments = @"–ExecutionPolicy Bypass -File ""C:\my\script.ps1"""; */

这些基本上是我要使用的基本样式代码命令。我一直有一个问题 - executionpolicy unrestricted。当我像上面一样在 powershell 中输入它时,它工作得很好。

此外,powershell 中与 cmd.exe /k 相当的编码是什么,因此命令提示符 window 保持打开状态以进行故障排除?

在看到您的错误后,我可以肯定地说错误来自于您正在 运行 的 sfc 命令。命令正在执行中。

执行策略是关于如何处理脚本文件的,所以它对命令运行没有立即影响(除非你在命令中引用脚本文件)。恐怕这对您的特定问题没有帮助。


是什么让您认为您的执行政策不起作用?

由于您没有在未注释的代码中使用 -File 参数,因此执行策略应该无关紧要。

cmd.exe /k 的类似 powershell 命令是 powershell.exe -NoExit

Answer found on Whosebug(click here)

...
using System.Diagnostics;
...

private void button4_Click(object sender, EventArgs e)
{
    string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string snat = Environment.GetEnvironmentVariable("windir") + @"\sysnative\sfc.exe";

    Process a = new Process();
      a.StartInfo.FileName = snat;
      a.StartInfo.Arguments = "/SCANNOW";
      a.StartInfo.UseShellExecute = false;
      a.StartInfo.RedirectStandardOutput = true;
      a.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
      a.StartInfo.CreateNoWindow = true;
    a.Start();

    string output = a.StandardOutput.ReadToEnd();
    a.WaitForExit();

    MessageBox.Show("DONE!");
}
catch
{
MessageBox.Show("error!");
}