Pipeline operator

We will start with the most important operator for PowerShell: the pipeline operator. It is getting a separate section, but it would normally be subordinated to the special operators. This might be the biggest challenge for most people. It can be extremely powerful but, sometimes, it can be very hard to debug the code if it is not working as intended. In general, a pipeline sends the output of the preceding function or cmdlet to the next one. Its output is bound to the parameters of the following cmdlets, by type. The pipeline always executes from left to right. Let's take a look at how this appears, in a very simple way:

# Gets all services and pipes them into the cmdlet Stop-Service
# By using the flag -WhatIf it is not really executing the code, but showing what it would do.
Get-Service | Stop-Service -WhatIf

#Piping is very often to export data
Get-Service | Export-Csv -Path 'c: empServices.csv'

#And also to visualize data
Get-Service | Out-GridView

These examples are very easy, but the lines of code using pipelines can get very long. Keep in mind that it may look very neat to use a single line to accomplish more complicated tasks. But, if you make any errors or need to troubleshoot the code later on, these long lines of code are unhandy. A recommendation is to use variables with good names to save the data in between, instead of creating challenging, long code lines with more than four pipelines. That is how you can identify whether the writer of a script had some software development background. Software developers write quite well most of the time, documenting code using many $variables and combining them in small steps later on. Administrators like to create single lines of code that just fulfill their required tasks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.83.150