c# - 如何使用 C# 执行 PowerShell 脚本

标签 c# asp.net .net windows powershell

我需要使用 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/

相关文章:

c# - Parallel ForEach 在不同的场合给出不同的结果

c# - SqlCeConnection 和 SqlConnection C# 有什么区别?

asp.net - 在ASP.NET中如何识别/处理404异常?

.net - 为什么 Socket.BeginReceive 会丢失 UDP 数据包?

.net - 命令失败后 Npgsql 不提交事务

C# 全屏控制台?

c# - 正则表达式使用搜索文本中的值/变量替换/搜索

asp.net - 使用 window.external.Sub1() 从嵌入式 GeckoWebBrowser 调用 VB Sub;

asp.net - 在 ASP.NET 中创建 Web API

c# - BackgroundColor Items ComboBox WPF