如何使用 C# 执行 PowerShell 脚本

Ija*_*jas 6 .net c# windows asp.net 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();
Run Code Online (Sandbox Code Playgroud)

这是行不通的。我该如何修复它?

我有一个 PowerShell 脚本文件,有时它会传递参数。

Ste*_*Ste 11

这里的答案都没有帮助我,但这个答案确实对我有帮助,并且是从这篇博客文章中摘取的,因此归功于作者 Duane Newman。

https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/

以下是在 Visual Studio 中创建控制台应用程序时运行 PowerShell 脚本的完整代码,该应用程序将绕过任何限制。

只需将ps1File下面的变量更改为您的需要即可。

// Code taken from: https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/
// Author: Duane Newman

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);

        }
    }
}

Run Code Online (Sandbox Code Playgroud)


pos*_*ote 5

从 C# 运行 .ps1 是一件非常常见的事情,网络上有许多示例,Youtube 上的视频展示了如何/带有示例。

从 C# 代码调用 Powershell 脚本

public static int RunPowershellScript(string ps)
{
int errorLevel;
ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("powershell.exe", "-File " + ps);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;

process = Process.Start(processInfo);
process.WaitForExit();

errorLevel = process.ExitCode;
process.Close();

return errorLevel;
}
Run Code Online (Sandbox Code Playgroud)

以及查看这些 stackoverflowthreads。

从 C# 调用 PowerShell 脚本文件 (example.ps1)

什么时候我们需要将 UseShellExecute 设置为 True?