Donnerstag, 24. September 2015

PowerShell Tip of the Day

Yesterday I talked about Out-GridView. Today I want to continue here and demonstrate what useful stuff you can do.

Lets imagine you want to write a quick script, which let you select multiple processes to be killed. This is a very common task for help desks.

We already saw, that Out-GridView lets you display processes (or any other objects) in a nice table view. If you take a deeper look on it, you will see that you can very easy filter your output:

You can define a filter on every property. This could be helpful if you want to see which processes have a high memory usage for example or if you only want to see a specific program:

But how can we design a "kill processes"-script with that? Well, we need the ability to pipe your selection to Stop-Process. Is there anything out-of-the-box? Our little helper on those questions is the PowerShell help system "Get-Help" ;)

With "Get-Help Out-GridView" you can see that there is a Parameter "PassThru". If we add this to our command, everything we select in our GridView will be send down the pipeline. In our case we will add a "Stop-Process" to the end of our pipeline:

Get-Process | Out-GridView -PassThru | Stop-Process

If you run this command you will see an OK-Button on the bottom of the new GridView window. This will close the window and take everything selected to the next step on the pipeline. The pipe itself will be paused as long as the GridView is open.

So if I want to kill all notepad processes, I select all of them in my GridView and click "OK". And *boom* it will be piped to "Stop-Process" and - if possible - the selected processes will be killed.

So, go on and play around with the GridView. And may the pipe be with you! :)

Keine Kommentare:

Kommentar veröffentlichen