how to get output from Receive-Job in variable – powershell trick

how to get output from Receive-Job in to variable?

Based on my research is it not possible to assign output of Receive-Job to variable without writing on host, but there is any alternative which can allow us to pass all error, warning, success msg to output stream and write on host as well.

how can we do that ?

Below is command to get the $job  and receive the job output in $status1 . here we have used *>&1 which means pass all error, warning, information to output stream.

$status1=get-job -name $job | Receive-Job  *>&1

But the problem with above command is , it also print the output to host

you can use $status1 to see the outcome of the job

 

Here is full and tested script, you can modify as per your requirement

454-2

cls
$jobids=@()
$process = Get-Process |select -First 2 |select name
# adding one more process name to validate if the error getting captured in output stream
$process+="appppppppnnfnnfn"
foreach($process1 in $process)
{
$processname = $process1
$jobids+=Start-Job -ScriptBlock{ 
$ar=$args[0]
Get-Process $($ar.name)
write-host "$env:COMPUTERNAME and $ar"} -ArgumentList $processname
}

# Checking if all jobs are completed
foreach($jobid in $jobids)
{
do
{
write-host "waiting"
}
while((get-job -Name $($jobid.name)).State -eq "running")
}

# get job output
foreach($jobid in $jobids)
{
if((get-job -Name $($jobid.name)).State -eq "completed")
{
$job = get-job -Name $($jobid.name)
#if you dont want to print anything on host then use invoke or else you can directly use receive-job with *>&1
$status1 = Invoke-Command -ScriptBlock { Receive-Job -Job $job *>&1 }
write-host "output for $($jobid.name) is - $status1"
}
else
{
write-host "$($jobid.name) is $((get-job -Name $($jobid.name)).State)"
}
}

(Visited 782 times, 1 visits today)

Add a Comment

Facebook