.NET Core,  Powershell

X509Certificate is immutable on this platform. Use the equivalent constructor instead

Quick tip today. Recently I decided to switch to to Powershell Core as default on all my machines for my daily work and it’s working great (except a few corner cases where I’m forced to go back to Powershell Desktop due to some old module incompatibility). To do so, over the last few weeks I had to go through the modules and script I use the most and port them to Pwsh.

One of my cmdlets is meant to convert a certificate to and from its Base64 representation (this is useful to export certificates from Azure KeyVault for example), the heart of the code where the transformation happens looks like this:

$certObj = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certObj.Import($FilePath)
$BinCert = $certObj.GetRawCertData() 
[System.Convert]::ToBase64String($BinCert)

Unfortunately though, while testing the code on Powershell Core I got this error:

X509Certificate is immutable on this platform. Use the equivalent constructor instead

It turns out the problem is with how I was creating the certificate object and loading its data. To avoid the exception the solution is to go from this:

$certObj = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certObj.Import($FilePath)

To this:

$certObj = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($FilePath)

I didn’t spent too much time to figure out why the exception is thrown (especially considering the Import() method is available on .NET Core/Pwsh) but at least I hope this will save someone else some time (and a headache 😉).


I have never met a man so ignorant that I couldn’t learn something from him. – Galileo Galilei 

5 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.