CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Executing Asynchronous HTTP Requests Using `Invoke-RestMethod`

πŸ‘€ Views: 15 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-19
PowerShell HTTP asynchronous

This might be a silly question, but I'm reviewing some code and I've been banging my head against this for hours..... I'm trying to make asynchronous HTTP requests in PowerShell 7.3 using `Invoke-RestMethod`, but I'm running into a question where the requests do not seem to complete before my script moves on to the next line. I want to retrieve data from multiple APIs concurrently, but the response times are inconsistent. I’ve tried using `Start-Job` to handle multiple requests, but I can’t seem to access the results reliably. Here's a simplified version of what I'm doing: ```powershell $urls = @( 'https://jsonplaceholder.typicode.com/posts/1', 'https://jsonplaceholder.typicode.com/posts/2', 'https://jsonplaceholder.typicode.com/posts/3' ) $jobs = foreach ($url in $urls) { Start-Job -ScriptBlock { param($url) Invoke-RestMethod -Uri $url } -ArgumentList $url } $results = $jobs | Wait-Job | Receive-Job ``` When I run this, I get the expected data returned, but the execution time seems to be longer than expected, and sometimes I get the behavior: ``` Invoke-RestMethod : Unable to connect to the remote server ``` This happens especially when the APIs are slow to respond. I’ve also tried adjusting the timeout settings by using `-TimeoutSec`, but it doesn't seem to make a difference. Is there a more effective way to handle asynchronous HTTP requests in PowerShell or any specific techniques that would allow me to better manage the request timeouts? Any help would be appreciated! I'm working on a CLI tool that needs to handle this. Is there a better approach? My development environment is Windows. Am I missing something obvious? This issue appeared after updating to Powershell 3.10. Cheers for any assistance! I'm working in a Ubuntu 22.04 environment. Any advice would be much appreciated.