栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > .Net

如何让PowerShell invoke-restmethod 和 invoke-webrequest 忽略不工作的自签名证书

.Net 更新时间:发布时间: 百科书网 趣学号

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中运行成功。

 

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1065996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号