PowerShell Receive-Job Output To Variable Or File But Not Screen

Question:

I am trying to get the job details without outputting the data to the screen. However, regardless of what option I try, the job logs always get sent to the console. Any ideas on how to save the logs in a variable or file without outputting that data to console?

Answer:

You state that your job uses Write-Host output and that you’re running Windows PowerShell v5.1.

In order to also capture Write-Host output – which in v5+ is sent to the information stream (stream number 6)use redirection 6>&1:

Unfortunately, due to a known bug, you’ll still get console output as well (bug is still present in PowerShell Core 7.0.0-preview.5).

Catch-all redirection *>&1 normally routes all streams through the success output stream.

Unfortunately, due to the bug linked to above, the following streams cannot be captured or redirected at all when using background jobs or remoting:

  • verbose messages (4)
  • debug messages (5)

The only workaround is to capture the streams inside the job and save them to a file from there, and then access the files from the caller later.
Of course, this requires that you have control over how the jobs are created.

A simplified example:

Note that I’ve used a full path as the redirection target, because, unfortunately, in v6- versions of PowerShell script blocks executed in background jobs do not inherit the caller’s current location. This will change in PowerShell Core v7.0.

Source:

PowerShell Receive-Job Output To Variable Or File But Not Screen by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply