I face below error frequently whenever try to automate a website running self signed or invalid certificate, Here is my lab vCenter server for demo which is using self signed SSL certificate. This causes my script to fail whenever using Invoke-WebRequest to automate website. You can trust the certificate by adding it to trusted root certificate or you can ignore the certificate that what we generally do on browser.
Another error article: PowerShell Invoke-WebRequest The request was aborted Could not create SSL TLS secure channel
Invoke-WebRequest -Uri https://marvel.vcloud-lab.com
Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS
secure channel.
At line:1 char:1
+ Invoke-WebRequest -Uri https://marvel.vcloud-lab.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
You can create a .net type object to ignore the certificate with as shown in below command. After checking website with either Invoke-WebRequest or Invoke-RestMethod, It shows status code 200, which means good.
Add-Type adds a .NET Framework type to a PowerShell session. If a .NET Framework class is added to your PowerShell session with Add-Type, those objects may then be instantiated (with New-Object ), just like any .NET Framework object. Script is written in C# language.
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type) { $certCallback = @" using System; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class ServerCertificateValidationCallback { public static void Ignore() { if(ServicePointManager.ServerCertificateValidationCallback ==null) { ServicePointManager.ServerCertificateValidationCallback += delegate ( Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors ) { return true; }; } } } "@ Add-Type $certCallback } [ServerCertificateValidationCallback]::Ignore()
Another smaller script to ignore website SSL certificate.
add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Useful Articles
Get-PSRepository WARNING Unable to find module repositories
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send
Creating an internal PowerShell module repository
How to sign PowerShell ps1 scripts
PowerShell Convert MAC address to Link-local address IPv6