Search code examples
c#wpfmultithreadingpowershellasynchronous

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


I am a novice in C# and have a GUI in WPF where at some point it should automatically start executing Powershell scripts, but preferably one by one. As I see all methods run at once without waiting previous to finish, so my question is: what is better to use some kind of threads or async methods?

If I try to use task.WaitForExit(); then it freezes GUI, which is not acceptable. I have tried to use timer as well, but it looks like it doesn't see this it at all. Besides I have more ps1 files and several bat files, which need to be run one by one. Could you tell please which method is better to use and how to combine it with active GUI in this case?

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

    }
}

Solution

  • Process.Start() returns Process instance, which has Exited event. Subscribe to that event to receive notification when it finished:

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