Pawan Mishra
Pawan Mishra

Reputation: 7268

Create instance of type with params argument in PowerShell

I am trying to create an instance of given type in PowerShell using New-Object. The constructor of the type being instantiated is having an argument of type [string params]. For example,

public class Test
{
    public Test(params string[] data)
    {
        //
    }
}

If I try to instantiate the above type using following command:

$ins = New-Object Test

I am getting the following error:

System.Management.Automation.PSArgumentException: Constructor not found. Cannot find an appropriate constructor for type.....

What is the correct way of instantiating the above type? I don't want to pass any dummy or empty string as input parameter.

The above sample code was only for demonstration purposes. The class that I am trying to instantiate is StandardKernel from Ninject library. The class definition is given below:

public class StandardKernel : KernelBase
{
    public StandardKernel(params INinjectModule[] modules)
      : base(modules)
    {
    }

    public StandardKernel(INinjectSettings settings, params INinjectModule[] modules)
      : base(settings, modules)
    {
    }
}

The following code works fine in C#:

var kernel = new StandardKernel()

Upvotes: 0

Views: 1370

Answers (2)

Rynant
Rynant

Reputation: 24283

After understanding your issue better, I don't know of a way to create the object with pure PowerShell, but you could create a C# method that will return what you want (see the NewTest type below).

$code1 = @'
public class Test
{
    public string arguments;

    public Test(params string[] data)
    {
        if(data != null) arguments = string.Join(", ", data);
    }
}
'@

$null = Add-Type -TypeDefinition $code1 -OutputAssembly c:\temp\Test.dll -PassThru

$code2 = @'
public class NewTest
{
    public static Test GetTest()
    {
        return new Test();
    }
}
'@

Add-Type -TypeDefinition $code2  -ReferencedAssemblies c:\temp\Test.dll

[NewTest]::GetTest()

Upvotes: 3

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200283

Aside from the issue with the params keyword that @Rynant had pointed out, your class constructor expects a parameter, but you don't provide one when trying to instantiate an object.

You could instantiate the object with an empty string to deal with this:

$src = @"
public class Test {
    public Test(params string[] data) {
        //...
    }
}
"@

Add-Type -TypeDefinition $src
$ins = New-Object Test ''

or you could overload the constructor:

$src = @"
public class Test {
    public Test(params string[] data) {
        //...
    }
    public Test() : this("") {}
}
"@

Add-Type -TypeDefinition $src
$ins = New-Object Test

Upvotes: 1

Related Questions