Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

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

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...