1

I'm using powershell v5 to call an internal API using TLS1.2 with a self-signed cert. When I call the api I always get Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.

E.g.:

PS> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
PS> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
PS> $url = "https://someinternalserver/blah"
PS> $response = Invoke-WebRequest $url
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1

(I've looked in the error object but I don't see anything helpful.)

However if I call the same URL using an instance of WebClient, then the call using WebClient AND all subsequent powershell calls works fine:

PS> $webClient = New-Object System.Net.WebClient
PS> $str = $webClient.DownloadString($url)
PS> Write-Host $str
body of request
PS> $response = Invoke-WebRequest $url
PS> Write-Host $response.Content
body or request

I'm not sure what's going on, but I suspect it has something to do with the self-signed cert, or the crypto. Here's what chrome says about the crypto: enter image description here

I've used powershell to call APIs with self-signed certs before but never had these kind of issues.

Resolution: I'd like to call the API without first using WebClient. Thanks.

  • Thanks a lot! This question is a solution to my issue. I'd love to know a proper solution for this as well, but it solves the main problem of me not being able to execute invoke cmdlets at all! Dumping the result of $webClient.DownloadString and caring on with a script is a dirty workaround but well at least it works. Thanks again. – user2395585 Aug 18 '23 at 11:11

1 Answers1

1

So dug into the error more and found this in an inner exception:

There is no Runspace available to run scripts in this thread.
You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. 
The script block you attempted to invoke was: $true

Which led me here: Powershell 3.0 Invoke-WebRequest HTTPS Fails on All Requests

Which led me here: https://stackoverflow.com/a/15841856/6311875

Using that code instead of the {$true} did the trick.

So, this further reinforces the idea that all questions are already answered on SO, you just have to look hard enough.

  • Ran into the same issue a while a go and you really need to dig very deep into the error. Definitely not something that shows up n the traces. – Alex Sarafian Oct 18 '17 at 05:24