One can call many LINQ methods in PowerShell with this simple notation:
[int[]] $numbers = 1..10000 [Linq.Enumerable]::Sum($numbers) It is even a relatively simple matter to include a lambda in a call:
[Func[int,int]] $delegate = { $n = $args[0]; if ($n % 3) { $n } else { -$n } } [Linq.Enumerable]::Sum($numbers, $delegate) What I am wondering, though, is how to call a generic LINQ method from PowerShell: is it even possible? I found this SO question that seems to indicate one can, but I have not determined how to apply that info to LINQ. (Plus, the fact that that is old information, it is quite possible that with PS version 5 there is a cleaner way to do it.)
So how could one call [Linq.Enumerable]::Cast<T>(...) or [Linq.Enumerable]::OfType<T>(...) properly in PowerShell?
2017.05.10 Update
OK, so based on @Mathias comment, let's stick with MakeGenericMethod. In C#, this incantation works:
var ofTypeForString = typeof(System.Linq.Enumerable).GetMethod("OfType").MakeGenericMethod(typeof(string)); var stuff = new object[] { 1.2, "abc", "def" }; var results = ofTypeForString.Invoke(null, new[] { stuff }); The piece I am still missing is how to translate typeof(System.Linq.Enumerable) to PowerShell. I thought that at least one of these should work but they all return null:
[System.Type]::GetType("System.Linq.Enumerable") [System.Type]::GetType("Linq.Enumerable") [System.Type]::GetType("Enumerable") I am sure I am missing something simple; suggestions?
typeof(System.Linq.Enumerable)to PowerShell.[Linq.Enumerable]Type.GetType(string)takes "[t]he assembly-qualified name of the type to get. See AssemblyQualifiedName." As such, you need to call it like[System.Type]::GetType("System.Linq.Enumerable,System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").GetMethod("OfType"). You should also just be able to do[System.Linq.Enumerable].GetMethod("OfType"), though.