繁体   English   中英

在 WPF 中逐步运行 Powershell 脚本文件(C#)

[英]Run Powershell script files step by step in WPF (C#)

我是 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)
    {

    }
}

Process.Start()返回具有 Exited 事件的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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM