0

In order to include a timeout, I am running the following job on Powershell:

> $job = Start-Job {$PSOut = net use * "<network path>"/persistent:no}
>> $job | Wait-Job -Timeout 30
>> if ($job.State -eq 'Running') {
>>   # Job is still running, cancel it
>>   $job.StopJob()
>> } else {
>>   # Job completed normally, get the result
>> $myArray = $job | Receive-Job

I would like the variable $PSOut to carry the output in the console window: "Drive X: is now successfully mapped with "

Or: "System error 53 encountered..." in case of an error message.

However, $PSOut always returns an empty value.

What I've already tried: Including the following in the Else branch. That way, I obtain the output if the script executes successfully, but am yet to find a way to do this when the script fails.

$PSOut = (Get-job | Receive-job)
Anupam
  • 37
  • 4

1 Answers1

0

I resolved this problem by including "2>&1" along with the Receive-Job command.

"$job = Start-Job {net use * " & in_NetworkPath & "/persistent:no};"
"$job | Wait-Job -Timeout 60;"
"If ($job.State -eq 'Running')"
   "{$job.StopJob();"+ _
   "$PSOut = Receive-Job $job 2>&1 | Out-String;"
   "throw "Error encountered: Operation timed out" }"
"else"
   "{if ($job.Childjobs[0].Error)"
      "{$PSOut = Receive-Job $job 2>&1 | Out-String; Throw $PSOut }"
   "else"
      "{$PSOut = Receive-Job $job | Out-String}}"

This works because Powershell seems to allow the assignment to a variable from Receive-Job only if the text value is in the information stream. The operation 2>&1 moves the text output from the error stream to the information stream. However, you must take note that this would prevent Powershell from throwing the text as an error message.

You can read more about the 2>&1 operation [here][1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-7

See also: Powershell: get output from Receive-Job

Anupam
  • 37
  • 4