PowerShell LINQ with Short Aliases
Seb Nilsson
Posted on March 24, 2020
Most modern applications or code today deal with some kind of filtering or querying. In C# and .NET, we have Language Integrated Query (LINQ), which we also have access to in PowerShell, because it's built on .NET.
To list the top 10 largest files in the Windows temporary folder, which is larger than 1 Mb and starts with the letter W, skipping the first 5, ordering by size, the C#-code with LINQ would look somewhat like this:
new System.IO.DirectoryInfo(@"C:\Windows\Temp")
.GetFiles()
.Where(x => x.Length > 1024 && x.Name.StartsWith("W"))
.OrderByDescending(x => x.Length)
.Select(x => new { x.Name, x.Length })
.Skip(5)
.Take(10)
.ToList()
.ForEach(x => Console.WriteLine($"{x.Name} ({x.Length})"));
The equivalent logic in PowerShell has a bit of a more daunting syntax, especially if you're not used to it:
Get-ChildItem "C:\Windows\Temp" `
| Where-Object {$_.Length -gt 1024 -and $_.Name.StartsWith("W")} `
| Sort-Object {$_.Length} -Descending `
| Select-Object -Property Name, Length -First 10 -Skip 5 `
| ForEach-Object {Write-Host "$($_.Name) ($($_.Length))"}
That's a bit explicit and verbose , but if you use the command
in PowerShell, you will see a lot of useful aliases, which make the syntax a bit terser and easier to get an overview of:
Get-Alias
gci "C:\Windows\Temp" `
| ?{$_.Length -gt 1024 -and $_.Name.StartsWith("W")} `
| sort{$_.Length} -Descending `
| select Name, Length -First 10 -Skip 5 `
| %{write "$($_.Name) ($($_.Length))"}
In a real scenario, you probably wouldn't write each result to the console, but let PowerShell present the result in its default grid format.
Posted on March 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.