C# 在Windows系统下 通过 PowerShell 调用Python库进行交互

发布时间 2023-09-18 21:23:43作者: 初久的私房菜

PwoerSheel调用代码

  public class PowerShellScriptRunner
  {
      public static async Task<string> ExecutePowerShell(string workDirectory, string command, string outputIndicator)
      {
          var processInfo = new ProcessStartInfo
          {
              FileName = "powershell.exe",
              Arguments =
                  $"-ExecutionPolicy Bypass -Command \"{command}\"",
              RedirectStandardOutput = true,
              RedirectStandardError = true,
              UseShellExecute = false,
              CreateNoWindow = true,
              WorkingDirectory = workDirectory
          };

          using var process = new Process();
          process.StartInfo = processInfo;
          process.Start();

          try
          {
              await process.WaitForExitAsync(new CancellationTokenSource(10000).Token);
          }
          catch (TaskCanceledException e)
          {
              var error = string.Empty;
              try
              {
                  error = await process.StandardError.ReadToEndAsync();
              }
              catch (Exception)
              {
                  // ignored
              }

              return default;
          }

          if (process.ExitCode < 0)
          {
              string errors = await process.StandardError.ReadToEndAsync();
              throw new Exception(errors);
          }
          else
          {
              var processOutput = process.StandardOutput;

              if (string.IsNullOrEmpty(outputIndicator)) return await processOutput.ReadToEndAsync();

              while (await processOutput.ReadLineAsync() is { } block)
              {
                  if (block == outputIndicator)
                  {
                      return await processOutput.ReadToEndAsync();
                  }
              }
              return await processOutput.ReadToEndAsync();

          }
      }

  }

外部使用代码

PowerShellScriptRunner.ExecutePowerShell(启动PowerSheel窗口的路径, 需要执行的脚本代码, "");