ProcessHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Threading.Tasks;
  5. using Debug = UnityEngine.Debug;
  6. using Path = System.IO.Path;
  7. namespace ET
  8. {
  9. public static class ProcessHelper
  10. {
  11. public static System.Diagnostics.Process PowerShell(string arguments, string workingDirectory = ".", bool waitExit = false)
  12. {
  13. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  14. {
  15. return Run("powershell.exe", arguments, workingDirectory, waitExit);
  16. }
  17. else
  18. {
  19. return Run("/usr/local/bin/pwsh", arguments, workingDirectory, waitExit);
  20. }
  21. }
  22. public static System.Diagnostics.Process Run(string exe, string arguments, string workingDirectory = ".", bool waitExit = false)
  23. {
  24. //Log.Debug($"Process Run exe:{exe} ,arguments:{arguments} ,workingDirectory:{workingDirectory}");
  25. try
  26. {
  27. bool redirectStandardOutput = false;
  28. bool redirectStandardError = false;
  29. bool useShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  30. if (waitExit)
  31. {
  32. redirectStandardOutput = true;
  33. redirectStandardError = true;
  34. useShellExecute = false;
  35. }
  36. ProcessStartInfo info = new ProcessStartInfo
  37. {
  38. FileName = exe,
  39. Arguments = arguments,
  40. CreateNoWindow = true,
  41. UseShellExecute = useShellExecute,
  42. WorkingDirectory = workingDirectory,
  43. RedirectStandardOutput = redirectStandardOutput,
  44. RedirectStandardError = redirectStandardError,
  45. };
  46. System.Diagnostics.Process process = System.Diagnostics.Process.Start(info);
  47. if (waitExit)
  48. {
  49. process.WaitForExit();
  50. }
  51. return process;
  52. }
  53. catch (Exception e)
  54. {
  55. throw new Exception($"dir: {Path.GetFullPath(workingDirectory)}, command: {exe} {arguments}", e);
  56. }
  57. }
  58. }
  59. }