38

First of all, i`m .NET developer and LOVE LINQ and extension methods in C#. But when i scripting i need something equivalent to Enumerable extension methods

Can anybody give me any suggestion/explain best practice about how to work in such scenarios in Powershell. For example, assume i want to take max element from array:

$arr = @(2, 1, 3)
$max = $arr.MAX() #?? what should i do in this case?

3 Answers 3

56

Use the Measure-Object command:

C:\PS> 2,1,3 | Measure-Object -Maximum


Count    : 3
Average  :
Sum      :
Maximum  : 3
Minimum  :
Property :

Or to get just the max:

C:\PS> (2,1,3 | Measure -Max).Maximum

There's also a Minimum, Average and Sum available as you can see from above. But you have to tell PowerShell to compute those with parameters to Measure-Object e.g. -Sum -Average etc.

Sign up to request clarification or add additional context in comments.

Comments

14

Keith correctly mentions PowerShell equivalents to some LINQ extension methods. Note that you can call most extension methods from PowerShell, you just can't invoke them like they are members.

Extension methods are really just static methods with some extra rules in C# to allow them to be called like members.

PowerShell doesn't implement any of those rules, but that doesn't stop you from calling them as static methods, e.g.

[System.Linq.Enumerable]::Average([int[]](1..10))

4 Comments

what about methods with Func? Any<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
Possible but a little painful because type deduction isn't as powerful as it could be: [System.Linq.Enumerable]::Any([int[]]@(1..10), [System.Func[int,bool]]{ $args[0] -gt 5 })
So, what should i do in such cases?
I'm not sure what you're asking. With casts, type deduction is often unnecessary (as my example shows.) If type deduction isn't possible (e.g. the return type of a generic method), then you must resort to reflection or C# - PowerShell has no syntax to explicitly specify the type parameters.
1

$arr | foreach { if($max -lt $_ ) {$max = $_ }};$max

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.