How do I capture output of Receive-Job?

What am I doing wrong below that neither of variables are being populated?

Invoke-Command -ComputerName localhost -ScriptBlock {Restart-Service -DisplayName d* -Verbose -WhatIf} -AsJob
Receive-job * -ErrorVariable RemoteErr -OutVariable output -Wait:$true
Write-Host $RemoteErr + $output

$x = Receive-Job

Would be how I’d do it.

Does not work

Invoke-Command -ComputerName localhost -ScriptBlock {Restart-Service -DisplayName d* -Verbose -WhatIf} -AsJob
$out = Receive-job * -ErrorVariable RemoteErr -OutVariable output -Wait:$true 
Write-Host $RemoteErr + $output
Write-Host $out

Well, lose the -OutVariable, as a first step.

But also, I think I see what the problem is.

PowerShell has five pipelines: Output, Verbose, Warning, Error, and Debug. Does Restart-Service actually produce any Output? That’s all you’re capturing either your way or my way. You’ve told it to produce Verbose text, sure - but that’s a different pipeline.

Unfortunately, there’s no common “-VerboseVariable” parameter that you can use to capture verbose output from a remotely run command. One trick would be to put the Verbose text into the Output stream:

Do-Something -Verbose 4>&1 (this is from about_redirection)

That puts the Verbose output into the Output pipeline, which -OutVariable will capture.

Would that achieve more what you were thinking? You’ll notice that the Job objects (the child jobs, not the parent) should also provide access to the various pipelines, but I’m not sure if that’s exactly what you’re after.

You may also need to explicitly set $VerbosePreference=‘Continue’ in your script block, but you -shouldn’t- need to, so maybe try it without first.

Thanks. For anybody who is in the same position resulting code is below which captures both normal output as well as error output

Invoke-Command -ComputerName localhost -ScriptBlock {$VerbosePreference='Continue';Restart-Service -DisplayName d* -Verbose 4>&1} -AsJob
Receive-job * -ErrorVariable RemoteErr -OutVariable output -Wait:$true
Write-Host $RemoteErr + $output