1

In Powershell 2.0, I am starting a cmd.exe process in a new window using the following:

Start-Process cmd.exe "/k proc.cmd"

Is there a way to monitor and react to this process's standard output in realtime (e.g. executing a command when the process outputs "Completed") without hiding its console output?

Charlie Joynt
  • 4,411
  • 1
  • 24
  • 46
Orestis P.
  • 805
  • 7
  • 27
  • This might be useful: [redirecting-output-on-child-process-to-parent-process-powershell](http://stackoverflow.com/questions/11323922/redirecting-output-on-child-process-to-parent-process-powershell) but it looks like the answer to that question does wait for the process to finish before reading standard output... – Charlie Joynt Apr 12 '16 at 08:19
  • Thanks, you are right, the answer does wait for the process to finish. I updated my question to specify that I need to monitor the output in realtime since the process never ends on its own – Orestis P. Apr 12 '16 at 08:24
  • 1
    Unfortunately PSv2 doesn't have `Register-ObjectEvent` which can be used to "listen" to standard output/error events from a running process... I guess that's an answer that can be written another day. – Charlie Joynt Apr 12 '16 at 15:41
  • @CharlieJoynt You are right. Unfortunately I can't install Powershell 3.0 since the script may be distributed to other computers (That come with 2.0) over time. – Orestis P. Apr 12 '16 at 16:16

1 Answers1

2

Don't use start-process - you will see the output real time in your active console. If you need it this way, then

  • run your line inside job
  • use loop to periodically (for instance every 1s) get the jobs output via receive-job.

EDIT

This is the sample script that demonstrates what you want

$j = start-job { while(1) { Get-Random; sleep 1 } }
while($j.State -eq 'Running') {
   $out = Receive-Job -Job $j
   $out
   if ($out -like '*44*') { break }
   sleep 1
} 
majkinetor
  • 8,730
  • 9
  • 54
  • 72
  • I'm not sure I understand. I need to start the process in a new window and react to its output. I've tried using Start-Job but it makes the new process run in the background (Meaning no new window is created). – Orestis P. Apr 12 '16 at 11:08
  • You need to use `receive-job` to get the job output. Then you can react to it - you don't need a window for that – majkinetor Apr 12 '16 at 11:57
  • Starting it in a new window was a requirement but I may just wrap the batch command into another powershell script and use this. I will test it tomorrow morning and update. Thanks. – Orestis P. Apr 12 '16 at 16:13
  • What kind of requirement is that ? :) – majkinetor Apr 12 '16 at 16:20
  • You can do it in another window too, its entirely different script tho. – majkinetor Apr 12 '16 at 16:21
  • Unfortunately I can't wrap the batch command into another powershell script and use your solution, since the reaction to the output needs to happen in the main script (Which must spawn a new window for the process) – Orestis P. Apr 13 '16 at 06:20