如何使用多个命令创建.ps1文件和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不受限制。当我在PowerShell中输入类似于上面的内容时,它效果很好。如何使用多个命令创建.ps1文件和Set-ExecutionPolicy Unrestricted -force?

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

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

执行策略是关于如何处理脚本文件,因此它对立即运行的命令没有影响(除非在命令中引用脚本文件)。它不会帮助你解决你的特殊问题。


是什么让你觉得你的执行策略不起作用?

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

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

+0

“Windows资源保护不能启动修复服务”这是显示错误。我认为-executionpolicy不受限制可以解决这个问题。 – DDJ

+0

我关闭了受信任的安装程序“net stop TrustedInstaller”,并认为这可能有所帮助,但仍然存在“SFC/SCANNOW” – DDJ

Answer found on *(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!"); 
}