The pipeline - using output from a PowerShell cmdlet
suggest changeOne of the first questions people have when they begin to use PowerShell for scripting is how to manipulate the output from a cmdlet to perform another action.
The pipeline symbol |
is used at the end of a cmdlet to take the data it exports and feed it to the next cmdlet. A simple example is using Select-Object to only show the Name property of a file shown from Get-ChildItem:
Get-ChildItem | Select-Object Name
#This may be shortened to:
gci | Select Name
More advanced usage of the pipeline allows us to pipe the output of a cmdlet into a foreach loop:
Get-ChildItem | ForEach-Object {
Copy-Item -Path $_.FullName -destination C:\NewDirectory\
}
#This may be shortened to:
gci | % { Copy $_.FullName C:\NewDirectory\ }
Note that the example above uses the $_
automatic variable. $_
is the short alias of $PSItem
which is an automatic variable which contains the current item in the pipeline.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents