How do I capture output of Receive-Job?

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of GS GS 1 year, 4 months ago.

  • Author
    Posts
  • #32279
    Profile photo of GS
    GS
    Participant

    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
    
  • #32280
    Profile photo of Don Jones
    Don Jones
    Keymaster

    $x = Receive-Job

    Would be how I'd do it.

  • #32282
    Profile photo of GS
    GS
    Participant

    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
    
  • #32283
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #32284
    Profile photo of GS
    GS
    Participant

    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
    

You must be logged in to reply to this topic.