我需要使用 c# 执行 PowerShell 脚本
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"cmd.exe";
startInfo.Arguments = @"powershell -File ""C:\Users\user1\Desktop\power.ps1""";
startInfo.Verb = "runas";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
这不起作用。有人能帮我吗? 我有一个 PowerShell 脚本文件,有时它会传递参数
最佳答案
这里的所有答案都没有帮助我,但这个答案确实帮助了我,并且摘自这篇博文,因此归功于作者。
https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/
这是当您在 Visual Studio 中创建控制台应用程序时将运行 PowerShell 脚本的完整代码,该应用程序将绕过任何限制。
只需将 ps1File
变量更改为您下面的需要即可。
using System;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
InstallViaPowerShell();
}
public static void InstallViaPowerShell()
{
var ps1File = @"C:\Users\stevehero\source\repos\RGB Animated Cursors PowerShell\RGB Animated Cursors\install-scheme.ps1";
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\"",
UseShellExecute = false
};
Process.Start(startInfo);
}
}
}
关于c# - 如何使用 C# 执行 PowerShell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61486225/