Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 646
Tim Lovell-Smith Avatar asked Oct 13 '12 05:10

Tim Lovell-Smith


People also ask

How do you take an array as a parameter in a constructor in Java?

To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object. So how we can store that array in our class for further operations.

How do you create an array of objects in a constructor?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

How do you pass an array to a constructor in C++?

In c++ , the name of the array is a pointer to the first element in the array. So when you do *state = *arr , you store the value at arr[0] in the variable state. Show activity on this post. The name of an array is the address of the first element in it.

When allocating an array of objects what constructor is used to initialize all of the objects in the array?

When allocating an array of objects, what constructor is used to initialize all of the objects in the array? The default constructor.


1 Answers

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) 
like image 142
Keith Hill Avatar answered Oct 26 '22 20:10

Keith Hill