The good news is PowerShell v3 is much better at binding to generic methods (and reifying them?) and you often don't have to do anything special but call it as you would a normal method. I can't specify all of the criteria for which this now works, but in my experience certain situations with generic parameters still require workarounds even in PowerShell v4 (maybe its the existence or overloads or something similar).
Similarly I also sometimes have trouble passing a generic parameter to a method ... for instance passing a Func<T1, T2, TResult>
parameter.
One work-around that to me is much simpler than MakeGenericMethod or other approaches is to just put a quick C# wrapper class directly in my script, and let C# sort out all the generic mapping ...
Here is an example of this approach that wraps the Enumerable.Zip
method. In this example my c# class isn't generic at all but that isn't strictly speaking necessary.
Add-Type @'
using System.Linq;
public class Zipper
{
public static object[] Zip(object[] first, object[] second)
{
return first.Zip(second, (f,s) => new { f , s}).ToArray();
}
}
'@
$a = 1..4;
[string[]]$b = "a","b","c","d";
[Zipper]::Zip($a, $b);
This produces:
f s
- -
1 a
2 b
3 c
4 d
I'm sure there are better PowerShell ways to "Zip" two arrays but you get the idea. The real challenge that I dodged here was having a hard-coded (in the C# class) 3rd parameter to Zip
so I didn't have to figure out how to pass in that Func<T1, T2, TResult>
(Maybe there is a PowerShell way to do that as well?).