Search code examples
powershelltext-indent

Indent output of command (non-blocking) in powershell


I'm looking for a non-blocking way of indenting the output of a command in powershell, by non-blocking I mean the output of the command must be displayed as the process runs.

Start-Process is non-blocking, however I can't figure out how to indent the output.

& { } can be indented, however doesn't output anything until the process is finished.

I came across a similar question on here and the provided solution to that question is as follows:

$ping = & { ping -n 2 google.com } 2>&1
$ping | ForEach-Object {"    $_"}

The above code almost does exactly what I need it to, however it won't output anything until the process is completed.. which will not work for my use case.


Solution

  • The only blocking step is the variable assignment, so skip that completely and it'll work as expected:

    & { ping -n 2 google.com } 2>&1 |ForEach-Object {"    $_"}
    

    If you still want to capture the raw output from the application and store it in a variable, use Tee-Object:

    & { ping -n 2 google.com } 2>&1 |Tee-Object -Variable ping |ForEach-Object {"    $_"}