The underlying connection was closed.

have the following script

$AllProtocols = [System.Net.SecurityProtocolType]‘Ssl3,Tls,Tls11,Tls12’
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
#[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$JenkinsURL = “https://jenkins.test.net
Invoke-WebRequest -URI $JenkinsURL

The above code is working fine when I run it locally on Powershell ISE. But when I trigger it from octopus deployment it is giving me error

Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
12:01:00 Error
trust relationship for the SSL/TLS secure channel.
12:01:00 Error
At C:\Octopus\Work\20180622063026-248\Script.ps1:5 char:1
12:01:00
Error + Invoke-WebRequest -URI “https://jenkins.test.net
Any thoughts on this ?

Did you see this answer?

https://social.technet.microsoft.com/Forums/en-US/9088b529-007f-4d7e-a6eb-b5dcc4cc35f9/the-underlying-connection-was-closed-could-not-establish160trust-relationship-for-the-ssltls?forum=winserverpowershell

I ran into this recently. In my case, my root certs weren’t in place so I couldn’t trust the cert to make a connection.

If ISE is running as you, you might check the cert store for whatever account is running octopus deploy to set it any certs are missing.

Some other things that could be required is TLS or if you are leveraging self-signed certs (typically internal APIs):

...
            try {
                # Allow the use of self-signed SSL certificates.
                [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
                
                # Force TLS 1.2 protocol. Invoke-RestMethod uses 1.0 by default
                Write-Verbose -Message ('{0} - Forcing TLS 1.2 protocol for invoking REST method.' -f $MyInvocation.MyCommand.Name)
                [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
                
                $results = Invoke-RestMethod @restParams
            }...

I’m having this exact same issue when running a script from Jenkins. Did you ever get this working? It works fine when running it on the slave but I get the same error when running it in Jenkins.