Powershell: get output from Receive-Job

前端 未结 7 1587
误落风尘
误落风尘 2020-12-09 08:57

I have a collection of jobs that are running. When they complete I use receive-job and it writes the output to the screen. I\'d like to take that output and log it to a file

7条回答
  •  春和景丽
    2020-12-09 09:23

    If the job uses Write-Host to produce output, Receive-Job returns $null, but the results get written to the host. However, if the job uses Write-Output to produce output in lieu of Write-Host, Receive-Job returns a string array [string[]] of the job output.

    To demonstrate, enter this innocuous code at the PowerShell prompt:

    $job = Start-Job -ScriptBlock {
        [int] $counter = 0
        while ($counter -lt 10) {
            Write-Output "Counter = $counter."
            Start-Sleep -Seconds 5
            $counter++
        }
    }
    

    Wait about 20-30 seconds for the job to produce some output, then enter this code:

    $result = Receive-Job -Job $job
    $result.Count
    $result
    $result | Get-Member
    

    The $result object contains the strings produced by the job.

提交回复
热议问题