You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 7.2.3运行脚本时ICertificatePolicy类型找不到错误求助

解决PowerShell 7.2.3中ICertificatePolicy找不到的错误

问题重现

运行以下PowerShell脚本时出现编译错误:

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

错误信息:

Add-Type: (5,36): error CS0246: The type or namespace name 'ICertificatePolicy' could not be found (are you missing a using directive or an assembly reference?)
public class TrustAllCertsPolicy : ICertificatePolicy {
                                   ^
Add-Type: Cannot add type. Compilation errors occurred.
New-Object: 
Line |
  22 |  … vicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
     |                                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find type [TrustAllCertsPolicy]: verify that the assembly containing this type is loaded.

问题原因

ICertificatePolicy是.NET Framework专属的API,在.NET Core/.NET 5+中已被移除。而PowerShell 7.x基于.NET Core构建,因此原脚本中依赖该接口的代码无法正常编译运行。

解决方案

改用.NET Core/.NET 5+支持的ServerCertificateValidationCallback委托来实现信任所有证书的逻辑,替换后的脚本如下:

简化版

# 直接设置回调信任所有证书
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

完整版(保留自定义验证逻辑)

# 定义自定义证书验证逻辑
$trustAllCertificates = {
    param(
        [System.Object]$sender,
        [System.Security.Cryptography.X509Certificates.X509Certificate]$cert,
        [System.Security.Cryptography.X509Certificates.X509Chain]$chain,
        [System.Net.Security.SslPolicyErrors]$sslErrors
    )
    # 忽略所有SSL证书错误,返回true表示信任
    return $true
}

# 应用验证回调
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $trustAllCertificates

说明

ServerCertificateValidationCallback是.NET Core/.NET 5+中用于自定义证书验证的标准方式,它提供了比旧版ICertificatePolicy更灵活的参数(如证书链、SSL错误类型),能满足更复杂的验证需求。

内容的提问来源于stack exchange,提问作者Arbelac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:15:29