I have this command
for ($i=0; $i -gt -1; $i++) {
$path = "..."
ffmpeg -f dshow -i audio="Microphone (USB Microphone)" -y -t 00:10:00 -b:a 128k $path
}
I need to get the current state of the last line of the command output stream, then if the line remains unchanged (staled/freezing/hanging) over 5 seconds log "warning: the program is freezing. trying to restart...", then stop the process and re-start the command.
But I wonder, is it even possible? Thanks for your help.
You can use a job to run a program in the background, which enables you to monitor its output and check for timeout conditions.
Note:
The code below uses the
Start-ThreadJobcmdlet, which offers a lightweight, much faster thread-based alternative to the child-process-based regular background jobs created withStart-Job.Start-ThreadJobcomes with PowerShell (Core) 7+ and in Windows PowerShell can be installed on demand with, e.g.,Install-Module ThreadJob -Scope CurrentUser.Start-ThreadJobis compatible with the other job-management cmdlets, such as theReceive-Jobcmdlet used below. If you're running Windows PowerShell and installing the module is not an option, simply replaceStart-ThreadJobwithStart-Jobin the code below.The code uses a simplified
ffmpegcall (which should have no impact on functionality), and can be run as-is, if you place asample.movfile in the current directory, which will transcode it to asample.mp4file there.Due to applying redirection
2>&1to theffmpegcall, it is the combined stdout and stderr that is monitored, so that status and progress information, whichffmpegemits to stderr, is also monitored.So as to emit progress messages in place (on the same line), as direct invocation of
ffmpegdoes, a CR ("`r") is prepended to each and[Console]::Error.Write()rather than[Console]::Error.WriteLine()is used.Caveat: Writing to
[Console]::Errorbypasses PowerShell's system of output streams. This means that you'll neither be able to capture nor silence this output from inside a PowerShell session in which your script runs. However, you can capture it - via a2>redirection - using a call to the PowerShell CLI, e.g.:What constitutes a progress message is inferred from each line's content, using regex
'^\w+= ', so as to match progress lines such asframe= …andsize= …