Linq in PowerShell
Introduction
For those of you who are not familiar with LINQ (Language Integrated Query), it is a set of general-purpose extensions to the .NET Framework, which allow developers to create powerful query expressions in C# and VB that let them work more efficiently with data.
In this blog post, we will talk about how Linq can be used in PowerShell to simplify complex tasks while reducing time spent on repetitive laborious activities.
Solution
Suppose you want to get all processes greater than 250 MB. To achieve it, you filter the result of running Get-Process
cmdlet based in WorkingSet
property.
The LINQ Where
method in C# will look like as follows where processes would be a collection that stores all object related to running processes:
processes.Where(proc => proc.WorkingSet > 250*1024);
Since PowerShell supports .NET types, we can use the language feature like delegate, especially anonymous delegate type Func
and Action
which are the building blocks of Linq.
According to Microsoft documentation, Where
method requires Func
delegate type, thus we need to create script block that returns a value.
Proper casting is also required because PowerShell Where
method doesn’t have syntax to explicitly specify a generic parameter.
Therefore, our PowerShell linq will look like as follows:
[System.Diagnostics.Process[]]$processes = Get-Process
[Func[System.Diagnostics.Process,bool]] $delegate = { param($proc); return $proc.WorkingSet -gt 250mb }
[Linq.Enumerable]::Where($processes, $delegate)
First, we apply Get-Process
cmdlet and cast it properly. Then, we create script block and finally we apply the script block into PowerShell linq Where
method.
The same way also apply to other Linq methods like First
, Single
, etc.
Conclusion
Since PowerShell supports .NET type system, using Linq in PowerShell becomes easy, just remember to create script block as anonymous function and cast the object properly since PowerShell methods or functions mostly do not support type parameterization. Only after that we can apply the data source (collection) and script block into Linq method.