Press "Enter" to skip to content

Working with REST APIs in PowerShell Core 6.0

Joshua Stenhouse 2

I’m pumped to see PowerShell become a cross-platform open-source solution with the release of PowerShell Core 6.0. Ubuntu, Debian, CentOS, RHEL, OpenSUSE, Fedora, macOS, even Raspbian, can all now run PowerShell! Microsoft has taken my favorite scripting language and made it portable, future-proof, and I couldn’t be happier. Why? Because all your knowledge and skills built from your time working in PowerShell are not going away anytime soon and I’d argue they just significantly increased in value. But, with the move from a .NET framework to .NET Core, any of your scripts that leverage the .NET framework will more than likely break.

To test this out the first thing I did was run some of my scripts In PowerShell Core 6.0 to see what worked and didn’t. Immediately I hit a snag with the .NET framework code I use at the start of all my REST API scripts that bypasses any certificate errors:

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

This no longer works! I could trust the certificates on all the web servers I connect to, but this is a pain in the ass in my lab. So, how do you work around it? Do I have to go and trust all these certificates? Don’t panic because the fix is really easy. Simply add the below to all of your REST API calls instead:

Invoke-RestMethod -SkipCertificateCheck
Invoke-WebRequest -SkipCertificateCheck

Simple huh? I must admit I panicked at first as I couldn’t see this parameter on the Microsoft website:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1

But it’s in PowerShell Core 6.0! I don’t know about you, but I’m going to start porting all my scripts over to the future of PowerShell. I’ll share any other issues I find as I do it. Happy scripting,

Joshua

Leave a Reply

%d bloggers like this: