在遇到尝试进行 REST API 调用并避免自签名证书问题后,我试图更好地理解 PowerShell 中的 Add-Type。代码如下。
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
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("InternalApiKey", "d472f0e9-23c9-4fff-aec9-cc1f2d5d6a85")
$response = Invoke-RestMethod 'https://localhost:9443/api/GetStats/' -Method 'GET' -Headers $headers
$response | ConvertTo-Json
当我运行它时,它会因错误而中断。
“新对象:找不到类型 [TrustAllCertsPolicy]:验证是否已加载包含此类型的程序集。” 然后,因为失败了,我得到了错误,“Invoke-RestMethod:远程证书无效,因为证书链中的错误:PartialChain”
只是偶然发现它在 PowerShell 5.1.22000.282 中按预期工作而在 PowerShell 7.2.1 中没有。我可以进行哪些更改以使其在两个版本的 PowerShell 中都能正常工作?
更新:这个链接有一些代码可以让它在两个版本的 PowerShell 中运行。我接受了我所做的答案,因为它是最有帮助的,并且因为我正在分享另一个答案。 https://github.com/PowerShell/PowerShell/issues/7092