Estoy tratando de comprender mejor Add-Type en PowerShell después de encontrarme con un problema al intentar hacer una llamada a la API REST y evitar un problema de certificado autofirmado. El código es el siguiente.
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-JsonCuando ejecuto esto, se rompe con el error.
"Nuevo objeto: no se puede encontrar el tipo [TrustAllCertsPolicy]: verifique que el ensamblado que contiene este tipo esté cargado". Y luego, debido a que falló, aparece el error "Invoke-RestMethod: el certificado remoto no es válido debido a errores en la cadena de certificados: PartialChain"
Me topé con el hecho de que funciona como se esperaba en PowerShell 5.1.22000.282 y no en PowerShell 7.2.1. ¿Qué cambios puedo hacer para que funcione en ambas versiones de PowerShell?
Actualización: este enlace tiene un código para que funcione en ambas versiones de PowerShell. Acepté la respuesta que hice porque fue la más útil y porque estoy compartiendo esta otra respuesta. https://github.com/PowerShell/PowerShell/issues/7092
En PowerShell 7.x, los cmdlets web tienen un -SkipCertificateCheck que puede usar en su lugar:
$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/' -SkipCertificateCheck -Method 'GET' -Headers $headers Si el punto final ya está enviando JSON, también podría usar Invoke-WebRequest en su lugar (en lugar de dejar que Invoke-RestMethod convierta de JSON a objetos y luego vuelva con ConvertTo-Json ):
$response = Invoke-WebRequest 'https://localhost:9443/api/GetStats/' -SkipCertificateCheck -Method 'GET' -Headers $headers $response.Content # this now contains the body of the raw response from the API, eg. JSON/XML/whatever