Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture external command progress in PowerShell?

I'm using a PowerShell script to synchronize files between network directories. Robocopy is running in the background.

To capture the output and give statistics to the user, currently I'm doing something like:

$out = (robocopy $src $dst $options)

Once that is done, a custom windows form is presented with a multi-line text box containing the output string.

However, doing this way halts the script execution until file copy is done. Since all the other input screen are presented to the user as graphical dialogues, I would like to give user progress output in a graphical way.

Is there a way to capture the stdout from robocopy, on the fly ?

Then the next question would be:

How to pipe that output into a form with a text box?

like image 260
Raf Avatar asked Apr 14 '26 17:04

Raf


1 Answers

You can run the robocopy job in the background and keep checking on the progress.

Start-Job will start the process in the background
Receive-Job will give you all the data that has been printed so far.

$job = Start-Job -scriptBlock { robocopy $using:src $using:dst $using:options }

$out = ""
while( ($job | Get-Job).HasMoreData -or ($job | Get-Job).State -eq "Running") { 
    $out += (Receive-job $job)
    Write-output $out 
    Start-Sleep 1
}

Remove-Job $job
like image 90
Jawad Avatar answered Apr 17 '26 13:04

Jawad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!