Sunday, June 3, 2012

PowerShell – Understanding pipeline and extending pipeline to more than one line

When writing PowerShell script one command which goes in a long line reduces the readability of the command, this normally happens when you are taking output object of one cmdlet and passing it to another cmdlet. 

You would like to extend a long line command in multi-line to improve the readability:- 

First let me clarify what does pipeline means in PowerShell, as you know object returned by a cmdlet can be stored in a variable for later use or piped to a subsequent cmdlet as input for the subsequent cmdlet. A pipeline is a channel through which the output of a cmdlet can be passed to following cmdlet, the pipeline is represented by pipe char ‘|’

Here is an example of pipeline: - Output of Get-Service cmdlet which is SPTimerV4 service is piped to the next cmdlet Stop-Service which stops the SpTimerV4 service.


Get-Service SPTimerV4 | Stop-Service


Below are the ways how you can extend the pipeline to more than one line to improve readability.

Use Tick Mark (‘): You can use tick mark to break the line and continue the command in next line, PowerShell assumes that the subsequent line is the continuation of the current line.

Example:-

Get-Service –DisplayName *SharePoint* |
Stop-Service


Use Pipe Symbol (|) as last character of the line: When Pipe symbol is the last character of a line, it indicates that the command is not complete so Windows PowerShell continues the command with the subsequent line

Example:-

Get-Service –DisplayName *SharePoint* |
Stop-Service


Use a left curly brace ({): Curly braces are normally used to enclose the structure such as expression or a procedure. A left curly brace suggests that a structure follows.

No comments:

Post a Comment