Warm tip: This article is reproduced from serverfault.com, please click

Using Write-Progress to show console output from an executable?

发布于 2020-12-14 05:49:16

I have a Windows executable which I run from powershell using:

& $command | Out-Default

The command can take several minutes to run and will periodically output messages to the console to show it's status. When I run this executable through powershell using the above style, I see the messages that the executables outputs shown in the powershell window. It looks ok, but I'd like to begin using Write-Progress to show the status of the executing command.

Is there any way to dynamically feed the output of this executable (as it runs) to Write-Progress so that it can show a progress bar with the message set to the last line of output from the executable?

Questioner
DaveUK
Viewed
0
Mathias R. Jessen 2020-12-14 19:06:48

Relaying standard output messages as progress status updates can be done by simply piping the output from the executable to ForEach-Object and passing it to Write-Progress:

function Invoke-WithProgress
{
  param([string]$Path)

  $Actvity = "Executing '$Path'..."

  # This one is optional
  Write-Progress -Activity $Actvity -Status "Starting out!"

  & $Path |%{
    # Provide each new line of output as a status update
    Write-Progress -Activity $Actvity -Status $_
  }

  # Complete the progress actvity
  Write-Progress -Activity $Actvity -Completed
}

Invoke-WithProgress $command