【问题标题】:Run Powershell script files step by step in WPF (C#)在 WPF (C#) 中逐步运行 Powershell 脚本文件
【发布时间】:2020-02-12 05:28:28
【问题描述】:

我是 C# 的新手,并且在 WPF 中有一个 GUI,在某些时候它应该会自动开始执行 Powershell 脚本,但最好是一个接一个。正如我看到所有方法一次运行而无需等待之前完成,所以我的问题是:使用某种线程或异步方法更好?

如果我尝试使用 task.WaitForExit();然后它会冻结 GUI,这是不可接受的。我也尝试过使用计时器,但看起来它根本看不到它。另外我还有更多的ps1文件和几个bat文件,需要一个一个运行。 您能告诉我在这种情况下哪种方法更好用以及如何将它与活动 GUI 结合起来吗?

public partial class Start_deployment : Window
{
    public Start_deployment()
    {
        InitializeComponent();
        Run_scripts();
        System.Windows.Application.Current.Shutdown();
    }

    public void Run_scripts()
    {
        var ps1File = @"C:\test\Install.ps1";
        var startInfo = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = $"-ExecutionPolicy Bypass -WindowStyle Hidden -NoProfile -file \"{ps1File}\"",
            UseShellExecute = false
        };
        var task = Process.Start(startInfo);
        //task.WaitForExit();
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {

    }
}

【问题讨论】:

  • 为什么不改用 Power Shell gui?
  • 如果你通过Task.Run()在非gui线程上运行RunScripts方法怎么办?你可以吗?
  • @MarkKram 据我了解 PS 缺少线程支持...
  • 嗯,它确实有点:stackoverflow.com/questions/3325911/…

标签: c# wpf multithreading powershell asynchronous


【解决方案1】:

Process.Start() 返回Process 实例,该实例已退出事件。订阅该事件以在完成时收到通知:

public partial class Start_deployment : Window
{
    public Start_deployment()
    {
        InitializeComponent();
        Run_scripts();
    }

    public void Run_scripts()
    {
        var ps1File = @"C:\test\Install.ps1";
        var startInfo = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = $"-ExecutionPolicy Bypass -WindowStyle Hidden -NoProfile -file \"{ps1File}\"",
            UseShellExecute = false
        };
        var proc = Process.Start(startInfo);
        proc.Exited += OnProcessExited;
    }

    private void OnProcessExited(object sender, EventArgs eventArgs)
    {            
        // todo, e.g.
        // System.Windows.Application.Current.Shutdown();
    }
}

【讨论】:

  • 看起来很棒!唯一的问题是它没有到​​达 OnProcessExited 方法...
  • @Oleg_D,进程是退出还是继续在后台工作?可以通过 TaskManager 或 ProcessExplorer 确认吗?
  • 是的,PowerShell ISE 中仍有一个进程和停止按钮仍处于活动状态。
  • Exited 事件将在进程完成时发生。我想可以在 powershell 中调用 smth 之类的“退出”?
猜你喜欢
  • 2014-09-12
  • 2018-11-21
  • 2021-08-16
  • 2018-11-09
  • 2021-10-13
  • 2020-12-20
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
相关资源
最近更新 更多