Thursday, January 31, 2008

Care required passing arrays to .Net methods in Powershell

In Powershell, argument lists for .Net methods are treated as arrays:
$instance.MyMethod($arg1,$arg2);
...which can be confusing if you want to pass an array as a single argument:
$instance.MyMethod($myArray);

New-Object : Cannot find an overload for "MyMethod" and the argument count: ""
Instead, force the array-argument to be contained within a single-member array:
# Note the extra comma below
$instance.MyMethod(,$myArray);
Makes sense when you think about it, but definitely a gotcha.

[In my case, I was caught out with the byte[] overload constructor for a MemoryStream]

1 comment:

Mike said...

Thanks for taking the time to write this up - this just caught me out constructing an IPAddress instance.

Popular Posts