PowerShell HTTP GET JSON with a Hard Timeout
PowerShell
function Get-JsonUrl {
param(
[Parameter(Mandatory)][string]$Uri,
[ValidateRange(1, 300)][int]$TimeoutSec = 10
)
try {
$data = Invoke-RestMethod -Uri $Uri -Method Get -TimeoutSec $TimeoutSec `
-Headers @{ Accept = 'application/json' } -ErrorAction Stop
} catch {
throw "GET $Uri failed: $($_.Exception.Message)"
}
if ($null -eq $data) { throw "GET $Uri returned an empty body." }
$data
}