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
Thomas Lindell
Thank you you saved me a lot of time.
Mark McGill
Thanks so much! I had a similar scenario. Running on PS 5.1, it worked great. Running on Core, it gave me the same error message. I appreciate you sharing!
Mick Wood
MDaemon Mail Server v20.0.1
I had the same error running the code that is included with the latest version of MDaemon.
I changed it as per your instruction and it works flawlessly.
Thanks for taking the time to share!
Pingback:
Luka Petrovic
Bless you beautiful soul for the time this saved me!