powershelljobs

Suppress receive-job console output when the job uses write-host


I'm starting a job and I need to receive the output before the job finishes. It uses write-host instead of write-output, I know when I use write-output this shouldn't be a problem but assume I need to use write-host.

So as an example I have a job

$job = Start-Job -Name $taskId -ScriptBlock { Write-host "This is the job output, there is a keyword"; start-sleep 2 }

I need to retrieve the console output and check for a keyword there, so I use receive-job

$result = Receive-Job -Job $job -Keep -ErrorAction SilentlyContinue *>&1

I use *>&1 to be able to capture every output. But I need to suppress the console output and only assign the output to the variable. Unfortunately I cannot suppress the console log. Using Out-Null also does not populate the variable.

Is there a way to do this?

Thanks


Solution

  • You may be able to capture the host output from the Job by inspecting the .Information property of the child job. In this case you can also use Receive-Job however the Job host output will still be console output.

    $job = Start-Job -Name $taskId -ScriptBlock {
        Write-Host 'This is the job output, there is a keyword'
        Start-Sleep 2
    }
    $job | Wait-Job | Out-Null
    $hostOutput = $job.ChildJobs | ForEach-Object { $_.Information.ReadAll() }