CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Getting Process IDs of Background Jobs in a Loop

👀 Views: 333 💬 Answers: 1 📅 Created: 2025-08-27
powershell jobs background-jobs PowerShell

I'm working on a personal project and I'm trying to configure This might be a silly question, but I'm trying to manage multiple background jobs in PowerShell 7.3, but I'm running into issues when trying to retrieve the process IDs of jobs created in a loop. My goal is to start several instances of a script, capture their process IDs, and eventually stop them based on certain conditions. Here's the code I've written so far: ```powershell $jobs = @() 1..5 | ForEach-Object { $job = Start-Job -ScriptBlock { Start-Sleep -Seconds (Get-Random -Minimum 1 -Maximum 5) "Job $_ completed" } $jobs += $job } # Trying to retrieve PIDs of the jobs $jobPIDs = $jobs | ForEach-Object { $_.Id } Write-Host "Job PIDs: $jobPIDs" ``` The intention is to collect the job IDs after they have been initiated. However, when I run the above script, I get the following warning message: ``` Start-Job : Unable to get the job state for job "Job 1" - it has not been started yet. ``` This happens even though the jobs should be starting correctly. I’ve tried adding a delay after starting each job to ensure they are running, but that didn’t help. Am I missing something in how the jobs are being created or accessed? Also, I need to ensure that I can manage these jobs later, so capturing the correct identifiers is crucial. Any insights on how to properly manage these jobs and retrieve their process IDs would be greatly appreciated! What's the best practice here? I'm developing on Linux with Powershell. I'd really appreciate any guidance on this. I'm coming from a different tech stack and learning Powershell.