Learn PowerShell – Piping
Piping in PowerShell is awesomesauce and best explained by some examples, but firstly a quick explanation of piping, lets say we want to get a list of files from the c:\windows folder on your machine, order them by the last modified date and select the first 50 files and output the list to a text file in the current folder, simple requirements and here it is:-
Get-ChildItem | Sort-Object LastWriteTime -Descending | Select-Object -First 50| Out-File files.txt
- Set-Location is the cmdlet which is roughly the equivalent to the cd command found in a command prompt.
- Get-ChiLdItem is the cmdlet which is roughly the equivalent to the dir command found in a command prompt, but you can use it with objects, lists and so on.
- Sort-Object is the cmdlet to sort obviously and can be used against your objects, lists and much more.
- Select-Object tis the cmdlet to select a number of objects (files, records, results), you can use this with -first, -last, -skip and much more
- Out-File will is the cmdlet to simply write output to a file.
Obviously a very simple example but you take A pass the results to B, B then does work on it, passes it to C and you got the idea. This is a how piping works and can yield the data your looking for quickly and in very little code indeed.
[…] Learn PowerShell – PowerShell Piping […]
[…] Learn PowerShell – Piping (Gregor Suttie) […]