Monday 16 January 2017

PowerShell Pipelines and Filtering Output – Part 3

In this post we will see how pipeline works and how you can filter output in PowerShell.

If you are new to PowerShell, I would recommend you to read my previous blog Part-1 and Part-2 before going through this post.

By understanding Pipelines and filtering objects, you take your PowerShell scripting to the next level. What pipeline does is it take a set of output (which is referred as object) and its sent across the pipe as an input to next cmdlet to do something.

Let's jump into some examples to see pipeline in action

First, I am going to start a notepad process. Then we will see how the process information can be sent as an input to stop/terminate the same process.




















-Confirm parameters comes handy when you writes scripts which is doing some changes to your system. Its always good to get a message like whether you want to perform this action

Now let's see internally on what logic these objects are passed over the pipeline


To demonstrate this, let's take the below example














This is a best example I have seen to explain the way how pipeline works. Thanks to Jeffery Snover who showed this in one of his presentation.

So let's do a Get-Help on Get-ChildItem to see list of parameters which accepts pipeline inputs























Then pass Get-Process to Get-Memeber which show us the list of methods, properties and typename for a object.






















In our case -Path parameter matches with the Path property in Get-Process

















So internally the path property of Calc process is passed as an input to Get-ChildItem. This is how pipelines work in PowerShell. By knowing the way how pipeline works will definitely help you to troubleshoot your scripts easily and write better codes as well.



















So that's it about pipelines. Now we'll see how to filter the output using where-object

Let's take Get-Process cmdlet for this demonstration. Assume you got a requirement to generate a report(html format) for every 15 minutes to get the list of process whose handles are greater than hundred and output should be sorted (descending).

Just the output of Get-Process











Filter our results using where-object. These are the different ways to write your where-object cmdlet. Everything gives you the same output.
























Now sort the output in descending order, covert the output to html and make it as a report.

Get-Process | where Handles -ge 1000 |Select-Object Name, Handles, Product, Description, Company | Sort-Object Handles -Descending | ConvertTo-Html | Out-File ProcessReport.htm












We just created a html report. But wait, I know what you might be thinking? Format doesn't looks good, right? Yes, but again this can be customized which I will cover in the future post.

In the next blog we will see how this can be done on multiple machines from one server

Cheers,
Naveen

1 comment: