PowerShell(3)Pipeline

7.    Pipeline

You can pipe the cmdlets up by using “|”. For example:

Dir | Sort-Object Length | Select-Object Name, Length |   ConvertTo-Html | Out-File report.html

It is object-oriented pipeline; PowerShell sends results as rich .NET objects through the pipeline. The PowerShell pipeline is always used, even when you provide only a single command. PowerShell attaches to your input the cmdlet  Out-Default which converts the resulting objects into text at the end of the pipeline.

Processing mode

2 types of processing, depends on individual pipe (cmdlet):

  1. Sequential: save the result of previous cmdlet until it’stotally finished, then process, then handle it to next pipe. The sequential cmdlet/function might cause  OOM problem if the result set is too big or a lot of error messages reported since all those are saved temporarily in memory.
  2. Real-time streaming.

Commonly used cmdlet/functions

Cmdlet/Function Description
Compare-Object Compares two objects or object collections and marks their differences
ConvertTo-Html Converts objects into HTML code
Export-Clixml Saves objects to a file (serialization)
Export-Csv Saves objects in a comma-separated values file
ForEach-Object Returns each pipeline object one after the other
Format-List Outputs results as a list
Format-Table Outputs results as a table
Format-Wide Outputs results in several columns
Get-Unique Removes duplicates from a list of values
Group-Object Groups results according to a criterion
Import-Clixml Imports objects from a file and creates objects out of them (deserialization)
Measure-Object Calculates the statistical frequency distribution of object values or texts
more Returns text one page at a time
Out-File Writes results to a file
Out-Host Outputs results in the console
Out-Host -paging Returns text one page at a time
Out-Null Deletes results
Out-Printer Sends results to printer
Out-String Converts results into plain text
Select-Object Filters properties of an object and limits number of results as requested
Sort-Object Sorts results
Tee-Object Copies the pipeline’s contents and saves it to a file or a variable
Where-Object Filters results according to a criterion

Format the result

You can use the highlighted ones to format the final output of the pipeline. There is one moreformat cmdlet: Format-Custom

To really see allthe object properties and not just the ones PowerShell “thinks” areimportant, use Format-Table and add a “*” to select all objectproperties.

Dir| Format-Table *

Still, the horizontal table design is unsuitable for more than just a handful of properties. This is why PowerShell uses Format-Listinstead of Format-Table  whenever there are more than five properties to display, and you should do the  same:

Dir| Format-List *

Widecard chars  are allowed to use in the format cmdlet parameters.  for example:

Get-Process i* | Format-Table name,pe*64                –list all columns begin withpe and end with 64

Get-WmiObject Win32_Share | Format-List [a-z]*    –exclude all columns that not start with analphabet letter.

Computed column

You can generate computed columns by using scriptblock. “$_”represent the current object. The block is braced by {}. For example:

Dir | Format-Table Name, { [int]($_.Length/1KB)}  —will create an integer column

Dir | Format-Table Name, Length, `
{(New-TimeSpan $_.LastWriteTime (Get-Date)).Days} –autosize  —will create a TimeSpan object column.

You can name the computed column:

$newName = @{Expression={ [int]($_.Length/1KB) }; Label=”KB” }
Dir | Format-TableName, $newName

Further process of the result

Sort/Group results

Following pipeline will show you how many processes you are running from each company,the result is descending by the count. Parameter “noelement” tell the Group-Object cmdlet not to generate the group object, since we only need acount.

Get-Process |Group-Object -propertyCompany -noelement | Sort-Object Count -descending

Here is mine, Am Ia Microsoft fan?

Count Name

—– —-

73 Microsoft Corporation

2 AMD

1 Adobe Systems, Inc.

1 Advanced Micro Devices…

1 Yahoo! Inc.

1 Adobe Systems Incorpor…

1 ATI Technologies Inc.

 

Following pipeline use the group object created by the Group-Object cmdlet:

Dir | Group-Object {$_.name.SubString(0,1).toUpper()} |
ForEach-Object { (“files start with “ + $_.Name); “—————-“; $_.Group}

Filter result

Get-Service | Where-Object { $_.Status -eq”Running” }

Get-WmiObject Win32_Service | ? {($_.Started -eq $false)-and ($_.StartMode -eq “Auto”)} | Format-Table

Trunk result row size

You can only display the columns that you are interested in:

Get-WmiObject Win32_UserAccount -filter “LocalAccount=TrueAND Name=’guest'” |
Select-Object Name, Disabled, Description

Redirect result

You can redirect the pipeline result to console, file,printer, into a string, or you can get the output suppressed. Here are the cmdlets to redirect output:

Get-Command -verb out

CommandType  Name        Definition
———–  —-         ———-
Cmdlet       Out-Default Out-Default [-InputObject <PSObject>]…
Cmdlet       Out-File    Out-File [-FilePath] <String> [[-Enco…
Cmdlet       Out-Host    Out-Host [-Paging] [-InputObject <PSO…
Cmdlet       Out-Null    Out-Null [-InputObject <PSObject>] [-…
Cmdlet       Out-Printer Out-Printer [[-Name] <String>] [-Inpu…
Cmdlet       Out-String  Out-String [-Stream] [-Width <Int32>]…

Example: save result as html file:

… | ConvertTo-Html | Out-File output.htm