invoke-webrequest 和invoke-restmethod 是PowerShell的两个模拟网站请求的命令。不过在一种场景下,它会报错。
Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
如何解决:
有的解决方法是使用这个命令:
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
但是,如果您使用的是最新版本的Windows 10/2016的Powershell,那么在使用Invoke-RestMethod
将会返回:
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
为什么会发生这种情况,它可以概括为:
将ServerCertificateValidationCallback设置为scriptblock将不适用于异步回调(在任务线程上发生的回调),因为另一个线程将没有运行空间来执行脚本.
这段代码解决了这个问题:这个来处理C#中的证书验证回调而不是脚本块:
function Disable-SslVerification
{
if (-not ([System.Management.Automation.PSTypeName]"TrustEverything").Type)
{
Add-Type -TypeDefinition @"
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class TrustEverything
{
private static bool ValidationCallback(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; }
public static void SetCallback() { System.Net.ServicePointManager.ServerCertificateValidationCallback = ValidationCallback; }
public static void UnsetCallback() { System.Net.ServicePointManager.ServerCertificateValidationCallback = null; }
}
"@
}
[TrustEverything]::SetCallback()
}
function Enable-SslVerification
{
if (([System.Management.Automation.PSTypeName]"TrustEverything").Type)
{
[TrustEverything]::UnsetCallback()
}
}
windows10中运行成功。