0

I have a process which sends output to a log file. I want to write a Powershell script to start this process, wait for it to finish, and whilst it is running, tail its log file to the console in real time.

I have tried this:

$procs = Start-Process "some_process.exe"
$logjob = Start-Job -Arg "some_logfile.log" -ScriptBlock {
    param($file)    
    Get-Content $file -wait | foreach { Write-Host($_) }
}
$procs | Wait-Process
$logjob | Stop-Job

... and other similar arrangements, using jobs. But it looks like the output of jobs is only available either after the job is stopped, or by sending 'events' from it, which sound like they're not really meant for rapid things like log messages (e.g. 100,000 lines in ~1 min).

Is there some other way to do this? My next option is to just call 'tail' from Start-Process, which would get the job done (I think - hopefully this doesn't have the same "wait for stop" output behaviour), but feels wrong.

Ben Hymers
  • 25,586
  • 16
  • 59
  • 84

1 Answers1

2

Job output isn't displayed unless you retrieve it from the job. Why don't you simply reverse what you're doing: start the process as a job, and tail the log file on the console:

$job = Start-Job -ScriptBlock { & "some_process.exe" }
Get-Content "some_logfile.log" -Wait

If you want the tail to terminate when the process terminates you could run both as jobs, and retrieve output from the log job while the other job is running:

$pjob = Start-Job -ScriptBlock { & "some_process.exe" }
$ljob = Start-Job -ScriptBlock { Get-Content "some_logfile.log" -Wait }

while ($pjob.State -eq 'Running' -and $ljob.HasMoreData) {
  Receive-Job $ljob
  Start-Sleep -Milliseconds 200
}
Receive-Job $ljob

Stop-Job $ljob

Remove-Job $ljob
Remove-Job $pjob
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I'd like the script to finish when the process finishes though :( As far as I can tell, `Get-Content -Wait` will wait until ctrl-c. – Ben Hymers Sep 22 '16 at 14:17
  • This will not work on Powershell 2.0 as HasMoreData is not cleared with Receive-Job. More info: https://stackoverflow.com/questions/10933732/hasmoredata-is-true-even-after-receive-job – Eduard G May 21 '20 at 15:33