I am trying to use powershell to make webrequests in parallel. I have a function "MakeRequest" that makes the type of request I need to make. This function works fine when run one-off, or when run in sequence. However, when I attempt to use either Start-Job or define a workflow to execute requests in parallel, I run into the error "You cannot call a method on a null-valued expression". The error is thrown on when i attempt to get the response from the web request "$response = $webRequest.GetResponse()"
What am i doing wrong / missing?
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$MakeRequest = {
param($machineName, [int]$port)
Write-Host $machineName $port
$url = "https://$machineName" + ":$port/path"
$webRequest = [net.WebRequest]::Create($url)
$webRequest.Headers.Add('MyHeader', 'MyValue')
# 10 Minute Timeout
$webRequest.Timeout = 600000
$returnCode = 1
$output = ""
Try {
Write-Host $webRequest
$response = $webRequest.GetResponse()
$statusCode = [int]$response.StatusCode
if ($statusCode -ne 200) {
Write-Host "Server $machineName did not return a 200, and instead returned a $statusCode"
Exit 1
}
[IO.Stream] $stream = $response.GetResponseStream()
[IO.StreamReader] $reader = New-Object IO.StreamReader($stream)
[string] $output = $reader.readToEnd()
$stream.flush()
$stream.close()
$returnCode = 0
} Catch [system.exception] {
[IO.Stream] $stream = $_.Exception.Response.GetResponseStream()
[IO.StreamReader] $reader = New-Object IO.StreamReader($stream)
[string] $output = $reader.readToEnd()
$stream.flush()
$stream.close()
} Finally {
Write-Debug "$machineName $output"
}
}
@("mach1, mach2, mach3" ) | ForEach-Object { Start-Job -ScriptBlock $MakeRequest -ArgumentList $_, 10443 }
Get-Job | Wait-Job
Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id }