Jawap
Jawap

Reputation: 2543

How to tail a log file while a process is running?

I'm running an exe from a PowerShell script. This executable writes its logs to a log file. I would like to continuously read and forward the logs from this file to the console while the executable is running.

Currently, I'm starting the exe like this:

$UNITY_JOB = Start-Job 
    -ScriptBlock { & "C:\Program Files\Unity\Hub\Editor\2019.2.11f1\Editor\Unity.exe" $args | Out-Null } 
    -ArgumentList $UNITY_ARGS

If I just do Get-Content $LOG_PATH -Wait at this point, I cannot detect when the exe terminates and the script blocks indefinitely.

If I start a second job for the logs, the output is not sent to the console:

$LOG_JOB = Start-Job -ScriptBlock { Get-Content $LOG_PATH -Wait }

(I need "real time" output, so I don't think Receive-Job would work)

Upvotes: 0

Views: 973

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5227

I'd use a loop which ends when the job's status is Completed:

# Just to mock the execution
$extProgram = Start-Job -ScriptBlock { Start-Sleep -Seconds 30}

$file = 'C:\path\to\file.txt'
do {
  cls
  Get-Content $file -Tail $host.ui.RawUI.WindowSize.Height
  Start-Sleep -Seconds 5 # Set any interval you need
} until ((Get-Job -Id $extProgram.id).State -eq "Completed")

Upvotes: 1

Related Questions