Phillip Scott Givens
Phillip Scott Givens

Reputation: 5464

Capture Verbose Stream from Job

I am trying to be a good a powerscript user and use Write-Verbose as per best practices, but I have no way to get the Verbose stream from a running Job.

$Job = Start-Job -Name "Scanning Work Item" -ScriptBlock{
    Write-Verbose "Write-Verbose" 
    Write-Host "Write-Host"
} 

while ($Job.HasMoreData -or $Job.State -eq "Running") {     
    Receive-Job -Job $Job -Verbose 
    Start-Sleep -Seconds 1
}

The output for this is

Write-Host

Please only answer with tested code as I have spent hours trying various permutations of Powershell script.

Upvotes: 4

Views: 3943

Answers (1)

mjolinor
mjolinor

Reputation: 68263

First of all, you're not getting any verbose ouput because you haven't changed the default VerbosePreference for the session.

As for reading Verbose ouput while the job is running, you can read each of the output stream buffers from the associated child job individually, without doing a Receive-job, and without affecting later output when you do the Receive-Job,

$Job = Start-Job -Name "Scanning Work Item" -ScriptBlock{
    $VerbosePreference = 'Continue'
    Write-Verbose "Write-Verbose" 
    Write-Host "Write-Host"
    Start-Sleep -Seconds 10
} 

Start-sleep -Seconds 2

$Verbose = $Job.ChildJobs[0].verbose.readall()

$verbose

while ($Job.HasMoreData -or $Job.State -eq "Running") {     
    Receive-Job -Job $Job 
    Start-Sleep -Seconds 1
}


Write-Verbose
VERBOSE: Write-Verbose
Write-Host

Upvotes: 6

Related Questions