0

I want to create a small C#-program which has multiple buttons which execute a Powershell script and put the results asynchronously into a textbox. I wanted to do it the following way:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            var ps1File = @"SomeScript.ps1";
            Process proc = new System.Diagnostics.Process();

            proc.StartInfo.FileName = "powershell.exe";
            proc.StartInfo.Arguments = $"-NoProfile -ExecutionPolicy unrestricted \"{ps1File}\"";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
  
            var err = "";    
            tbConsole.Text = "Loading printers ...";

            proc.OutputDataReceived += (o, e2) =>
            {
                if (e2.Data == null) err = e2.Data;
                else
                {
                    if (e2.Data == null) err = e2.Data;
                    else tbConsoleError.AppendText(e2.Data);
                }
            };

            proc.ErrorDataReceived += (o, e2) =>
            {
                if (e2.Data == null) err = e2.Data;
                else tbConsoleError.AppendText(e2.Data);
            };

            proc.Start();

            // and start asynchronous read
            proc.BeginOutputReadLine();

            proc.BeginErrorReadLine();
            // wait until it's finished in your background worker thread
            proc.WaitForExit();
            tbConsole.AppendText("... finished");    
        }

Now when I hit the button the sript runs but while editing the textboxes it gives me an error that I cannot edit the textbox as it is managed by a different thread.

When I now try to edit my code to use "invoke" and delegate I find that my MainWindow (objet-reference: "this") does not have an "invoke"-method. What am I doing wrong?

  • What would be the point of executing a PowerShell script to do this? Why not simply use C# code to process your data and cut out the extra steps that could potentially fail (for example, if there aren't enough permissions to open the script file, the file doesn't exits, etc.). – NightOwl888 May 23 '22 at 13:30
  • The Powershell does got some automatic processes, the .NET application is for executing those scripts on demand by users and visualizing the results. There is no input required by the scripts. – André Pletschette May 23 '22 at 13:33
  • [How do I get output from a command to appear in a control on a Form in real-time?](https://stackoverflow.com/a/51682585/7444103) – Jimi May 23 '22 at 17:00

0 Answers0