2

I'm trying to run a powershell script in my C# form application. The powershell script pings a certain machine every .5 seconds and displays an output until exited.

I can run the script and open it up in powershell, but I want the output to display the LIVE ping results in a C# form label (or ritchtextBox if that isn't possible)

Here's the code I currently have that runs the program externally.

 private void Btn_Ping_Click(object sender, EventArgs e)

{
    ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = 
@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
    proc.Arguments = 
@"//ctac.1800contacts.com/service/hd_image/tools/LatencyTest.bat " + 
Txt_Main.Text.Trim();
    Process.Start(proc);
    richTextBox1.AppendText("Started pinging " + Txt_Main.Text + 
 "\r\n");
    Txt_History.ScrollToCaret();
}

I expect the code to display an output within my windows form application, but not actually pull up powershell. Is this possible?

William
  • 23
  • 4
  • Batch files are not powershell scripts; the powershell in your code is not doing anything relevant, it's just running command prompt, so you can't use any of the integration between PS and C# to do things more directly. You'll have to consider it as running a process and getting the output, and this is the kind of thing you'll need to do: [Get Live output from Process](https://stackoverflow.com/questions/8808663/get-live-output-from-process), or https://stackoverflow.com/questions/4291912 or https://stackoverflow.com/questions/285760 – TessellatingHeckler Apr 02 '19 at 20:28
  • I've written a pair of codeproject articles a while ago that show how to do it: [How to run PowerShell scripts from C#](https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C) and [Asynchronously Execute PowerShell Scripts from C#](https://www.codeproject.com/Articles/18409/Asynchronously-Execute-PowerShell-Scripts-from-C) – jmik Apr 02 '19 at 22:07
  • Seems like a just horrible way to do this. Either just use powershell, or re-write it in C#. It's like using hauling stuff in a cargo van in a semi-truck... ya really don't need both, just one will do. – Erik Philips Apr 02 '19 at 23:05
  • Sorry, just for clarification - The code written was already there from someone else, I realized it wasn't a good way to handle this and am the one trying to change it. I'm just starting out learning C# and wasn't sure if there was a way to run the bat file passing in an argument (the computer name), and output the results live. – William Apr 03 '19 at 00:36

0 Answers0