How do I call New-Object for a constructor which takes a single array parameter?

ArraysPowershellParametersConstructor

Arrays Problem Overview


In PowerShell, I want to use New-Object to call a single-argument .Net constructor new X509Certificate2(byte[] byteArray). The problem is when I do this with a byte array from powershell, I get

> New-Object : Cannot find an overload for "X509Certificate2" and the argument count: "516".

Arrays Solutions


Solution 1 - Arrays

This approach to using new-object should work:

$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate `
      -ArgumentList @(,$bytes)

The trick is that PowerShell is expecting an array of constructor arguments. When there is only one argument and it is an array, it can confuse PowerShell's overload resolution algorithm. The code above helps it out by putting the byte array in an array with just that one element.

Update: in PowerShell >= v5 you can call the constructor directly like so:

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate]::new($bytes)

Solution 2 - Arrays

Surprisingly to me, I tried this and it seems it works:

[byte[]] $certPublicBytes = something
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate] $certPublicBytes
return $cert

I don't yet know by what magic it works, so your explanatory comments are appreciated. :)

(Note: I since found that using square-brackets-type-name as I did above, can also lead to other errors, such as 'Cannot convert value "System.Byte[]" to type "System.Security.Cryptography.X509Certificates.X509Certificate". Error: "Cannot find the requested object.' The explicit New-Object approach recommended by Keith seems better!)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim Lovell-SmithView Question on Stackoverflow
Solution 1 - ArraysKeith HillView Answer on Stackoverflow
Solution 2 - ArraysTim Lovell-SmithView Answer on Stackoverflow