Invoking a Powershell script and Displaying its output in a Windows Form ApplicationBest practice to save application settings in a Windows Forms ApplicationSetting Windows PowerShell path variableTerminating a script in PowerShellHow to run a PowerShell scriptPowerShell says “execution of scripts is disabled on this system.”Formatting Output of Hosted PowerShellTrying to run a powershell script in C#powershell displaying output from an invoke-espressionPowershell v2 use textbox to continously output textConvert my Powershell script into an c# Windows Form

Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

How to type dʒ symbol (IPA) on Mac?

What would the Romans have called "sorcery"?

Suffixes -unt and -ut-

How can I hide my bitcoin transactions to protect anonymity from others?

Why is "Reports" in sentence down without "The"

Why can't I see bouncing of a switch on an oscilloscope?

What would happen to a modern skyscraper if it rains micro blackholes?

XeLaTeX and pdfLaTeX ignore hyphenation

Find original functions from a composite function

What do you call a Matrix-like slowdown and camera movement effect?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

Why don't electron-positron collisions release infinite energy?

Prevent a directory in /tmp from being deleted

Why CLRS example on residual networks does not follows its formula?

If Manufacturer spice model and Datasheet give different values which should I use?

Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).

Book about a traveler who helps planets in need

Pronouncing Dictionary.com's W.O.D "vade mecum" in English

Why is the design of haulage companies so “special”?

How does one intimidate enemies without having the capacity for violence?

TGV timetables / schedules?



Invoking a Powershell script and Displaying its output in a Windows Form Application


Best practice to save application settings in a Windows Forms ApplicationSetting Windows PowerShell path variableTerminating a script in PowerShellHow to run a PowerShell scriptPowerShell says “execution of scripts is disabled on this system.”Formatting Output of Hosted PowerShellTrying to run a powershell script in C#powershell displaying output from an invoke-espressionPowershell v2 use textbox to continously output textConvert my Powershell script into an c# Windows Form






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I've got a powershell script that outputs to the console every 5 seconds, like so:



While($true)

Write-Output "test"
Start-Sleep -seconds 5



I want to have a windows form application that will allow the user to enter the filepath of the script, hit a button, and then display any further output from this script in a window like so:



enter image description here



However, I am running into trouble actually getting this script to startup. Based on reading different threads, here's what I've got at the moment:



private void button1_Click(object sender, EventArgs e)

string filepath = textBox1.Text;
if (File.Exists(filepath))

string s = "";
var info = new ProcessStartInfo();
Process process = new Process();

info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.FileName = "powershell.exe";
info.Arguments = filepath;

process.StartInfo = info;

process.Start();

s += process.StandardOutput.ReadToEnd();
process.WaitForExit();
textBox1.AppendText(s);


else

textBox1.Text = "Error: Invalid file path.";




Now, this does open a powershell window, so I know that it at least starts the process, but I'm not seeing it actually run my script, and I know that the file exists at the path I'm entering. When I run powershell.exe filepath in a command prompt terminal, the script runs fine.



The end goal is to have all output written to the white textbox on the right-hand side of the Form Desktop Application above and continually append to that textbox as the script gives output.










share|improve this question




























    0















    I've got a powershell script that outputs to the console every 5 seconds, like so:



    While($true)

    Write-Output "test"
    Start-Sleep -seconds 5



    I want to have a windows form application that will allow the user to enter the filepath of the script, hit a button, and then display any further output from this script in a window like so:



    enter image description here



    However, I am running into trouble actually getting this script to startup. Based on reading different threads, here's what I've got at the moment:



    private void button1_Click(object sender, EventArgs e)

    string filepath = textBox1.Text;
    if (File.Exists(filepath))

    string s = "";
    var info = new ProcessStartInfo();
    Process process = new Process();

    info.UseShellExecute = false;
    info.RedirectStandardOutput = true;
    info.FileName = "powershell.exe";
    info.Arguments = filepath;

    process.StartInfo = info;

    process.Start();

    s += process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    textBox1.AppendText(s);


    else

    textBox1.Text = "Error: Invalid file path.";




    Now, this does open a powershell window, so I know that it at least starts the process, but I'm not seeing it actually run my script, and I know that the file exists at the path I'm entering. When I run powershell.exe filepath in a command prompt terminal, the script runs fine.



    The end goal is to have all output written to the white textbox on the right-hand side of the Form Desktop Application above and continually append to that textbox as the script gives output.










    share|improve this question
























      0












      0








      0








      I've got a powershell script that outputs to the console every 5 seconds, like so:



      While($true)

      Write-Output "test"
      Start-Sleep -seconds 5



      I want to have a windows form application that will allow the user to enter the filepath of the script, hit a button, and then display any further output from this script in a window like so:



      enter image description here



      However, I am running into trouble actually getting this script to startup. Based on reading different threads, here's what I've got at the moment:



      private void button1_Click(object sender, EventArgs e)

      string filepath = textBox1.Text;
      if (File.Exists(filepath))

      string s = "";
      var info = new ProcessStartInfo();
      Process process = new Process();

      info.UseShellExecute = false;
      info.RedirectStandardOutput = true;
      info.FileName = "powershell.exe";
      info.Arguments = filepath;

      process.StartInfo = info;

      process.Start();

      s += process.StandardOutput.ReadToEnd();
      process.WaitForExit();
      textBox1.AppendText(s);


      else

      textBox1.Text = "Error: Invalid file path.";




      Now, this does open a powershell window, so I know that it at least starts the process, but I'm not seeing it actually run my script, and I know that the file exists at the path I'm entering. When I run powershell.exe filepath in a command prompt terminal, the script runs fine.



      The end goal is to have all output written to the white textbox on the right-hand side of the Form Desktop Application above and continually append to that textbox as the script gives output.










      share|improve this question














      I've got a powershell script that outputs to the console every 5 seconds, like so:



      While($true)

      Write-Output "test"
      Start-Sleep -seconds 5



      I want to have a windows form application that will allow the user to enter the filepath of the script, hit a button, and then display any further output from this script in a window like so:



      enter image description here



      However, I am running into trouble actually getting this script to startup. Based on reading different threads, here's what I've got at the moment:



      private void button1_Click(object sender, EventArgs e)

      string filepath = textBox1.Text;
      if (File.Exists(filepath))

      string s = "";
      var info = new ProcessStartInfo();
      Process process = new Process();

      info.UseShellExecute = false;
      info.RedirectStandardOutput = true;
      info.FileName = "powershell.exe";
      info.Arguments = filepath;

      process.StartInfo = info;

      process.Start();

      s += process.StandardOutput.ReadToEnd();
      process.WaitForExit();
      textBox1.AppendText(s);


      else

      textBox1.Text = "Error: Invalid file path.";




      Now, this does open a powershell window, so I know that it at least starts the process, but I'm not seeing it actually run my script, and I know that the file exists at the path I'm entering. When I run powershell.exe filepath in a command prompt terminal, the script runs fine.



      The end goal is to have all output written to the white textbox on the right-hand side of the Form Desktop Application above and continually append to that textbox as the script gives output.







      c# powershell windows-forms-designer






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 9 at 3:37









      jprueejpruee

      254




      254






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Try this code, take the "string s = process.StandardOutput.ReadToEnd();" and start the thread right before the process.WaitForExit(); then you can break out of the thread once the process exit. It is still possible that you may need to create a delegate function to print the text in your text box, if so look into delegate functions, easy to implement.



           Thread t = new Thread(ReadStart);
          t.Start(process);
          process.WaitForExit();


          public void ReadStart(object data)

          System.Diagnostics.Process p = (System.Diagnostics.Process)data;
          while(true)

          string s = p.StandardOutput.ReadToEnd();
          textBox1.AppendText(s);
          Thread.Sleep(1000);
          if (p.HasExited) break;







          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073750%2finvoking-a-powershell-script-and-displaying-its-output-in-a-windows-form-applica%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Try this code, take the "string s = process.StandardOutput.ReadToEnd();" and start the thread right before the process.WaitForExit(); then you can break out of the thread once the process exit. It is still possible that you may need to create a delegate function to print the text in your text box, if so look into delegate functions, easy to implement.



             Thread t = new Thread(ReadStart);
            t.Start(process);
            process.WaitForExit();


            public void ReadStart(object data)

            System.Diagnostics.Process p = (System.Diagnostics.Process)data;
            while(true)

            string s = p.StandardOutput.ReadToEnd();
            textBox1.AppendText(s);
            Thread.Sleep(1000);
            if (p.HasExited) break;







            share|improve this answer



























              0














              Try this code, take the "string s = process.StandardOutput.ReadToEnd();" and start the thread right before the process.WaitForExit(); then you can break out of the thread once the process exit. It is still possible that you may need to create a delegate function to print the text in your text box, if so look into delegate functions, easy to implement.



               Thread t = new Thread(ReadStart);
              t.Start(process);
              process.WaitForExit();


              public void ReadStart(object data)

              System.Diagnostics.Process p = (System.Diagnostics.Process)data;
              while(true)

              string s = p.StandardOutput.ReadToEnd();
              textBox1.AppendText(s);
              Thread.Sleep(1000);
              if (p.HasExited) break;







              share|improve this answer

























                0












                0








                0







                Try this code, take the "string s = process.StandardOutput.ReadToEnd();" and start the thread right before the process.WaitForExit(); then you can break out of the thread once the process exit. It is still possible that you may need to create a delegate function to print the text in your text box, if so look into delegate functions, easy to implement.



                 Thread t = new Thread(ReadStart);
                t.Start(process);
                process.WaitForExit();


                public void ReadStart(object data)

                System.Diagnostics.Process p = (System.Diagnostics.Process)data;
                while(true)

                string s = p.StandardOutput.ReadToEnd();
                textBox1.AppendText(s);
                Thread.Sleep(1000);
                if (p.HasExited) break;







                share|improve this answer













                Try this code, take the "string s = process.StandardOutput.ReadToEnd();" and start the thread right before the process.WaitForExit(); then you can break out of the thread once the process exit. It is still possible that you may need to create a delegate function to print the text in your text box, if so look into delegate functions, easy to implement.



                 Thread t = new Thread(ReadStart);
                t.Start(process);
                process.WaitForExit();


                public void ReadStart(object data)

                System.Diagnostics.Process p = (System.Diagnostics.Process)data;
                while(true)

                string s = p.StandardOutput.ReadToEnd();
                textBox1.AppendText(s);
                Thread.Sleep(1000);
                if (p.HasExited) break;








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 9 at 5:17









                faljbourfaljbour

                1,2082613




                1,2082613





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073750%2finvoking-a-powershell-script-and-displaying-its-output-in-a-windows-form-applica%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived