Raf
Raf

Reputation: 1757

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?

Upvotes: 3

Views: 552

Answers (1)

Jawad
Jawad

Reputation: 11364

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

Upvotes: 3

Related Questions