CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Parallel Execution of Background Jobs and Handling Job Results

👀 Views: 31 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
PowerShell BackgroundJobs Concurrency

I've been struggling with this for a few days now and could really use some help. I'm relatively new to this, so bear with me. I'm working on a project and hit a roadblock. I've been trying to run multiple PowerShell background jobs in parallel using PowerShell 7.3, but I'm running into issues when attempting to handle their results once they're completed. I'm using the `Start-Job` cmdlet to kick off the jobs and then trying to retrieve the results using `Receive-Job`. However, it seems like I need to access the output of the jobs correctly, and I'm getting the following behavior message: ``` Receive-Job : You want to call a method on a null-valued expression. ``` Here's a simplified version of my code: ```powershell $jobs = @() foreach ($i in 1..5) { $jobs += Start-Job -ScriptBlock { Start-Sleep -Seconds 2 "Result from Job $using:i" } } # Wait for all jobs to complete $jobs | ForEach-Object { Wait-Job $_ } # Attempting to retrieve results foreach ($job in $jobs) { $result = Receive-Job -Job $job -Keep if ($null -ne $result) { Write-Output "Job Result: $result" } else { Write-Output "No result for job $job" } } # Cleaning up jobs $jobs | ForEach-Object { Remove-Job $_ } ``` What I expect is to see the output from each job, but instead, I'm not getting any result or I end up with that null-valued expression behavior. I've checked that the jobs are indeed running and completing, but I'm not sure how to properly handle the output. I've also tried using `Get-Job` to inspect the job status, and it shows that the jobs are 'Completed'. Is there something I'm missing in how I'm retrieving or processing the job results? Any help or pointers would be greatly appreciated. What's the best practice here? I'm working on a API that needs to handle this. Is there a better approach? The project is a CLI tool built with Powershell. What's the correct way to implement this?