PowerShell 103 – Pipelines

For this PowerShell 103 we’re going to do some theory again, luckily I’ve mixed it with some practical stuff. My intention is to keep things as practical and hands on as possible. For this post we’re going to handle pipelines and the practical usages of pipelines.

Pipelines

If you’ve followed the series then you’ve already seen them in my last blog in both example scripts. The “|” character is called a pipeline character. You can use this character to take output from the previous command and feed it to the next.

So for example:

Retrieves all files and folders in C:\Windows\Temp (recursively). These file are then fed to the Remove-Item cmdlet which forcefully removes them. Keep in mind that not all cmdlets support pipeline input.

One of the other common uses is selecting parts of the output. So for example:

This doesn’t give you a complete table like Get-ChildItem normally does but it only outputs the object which is called “Name”. This is mainly useful when trying to limit the data you’re retrieving (or passing on using another pipeline). You can also try replacing Select for Sort. I think you can imagine for yourself what that does. You can try both versions of the above command if you want.

One of the things I personally use very often is filtering. For example:

This command only retrieves the files that have a filename that ends with “.log”. I’ve included the Where-Object in this command to make the filtering possible. Whenever you use Where-Object the comparison you want to use is enclosed within “{}”. Another thing you can learn of this is that you can use $_  to reference to the data retrieved in the first object. In this case we used it to select the “Name” property and use -like (comparison operator) to compare it to the string “*.log”. Where the “*” indicates a wildcard and represents one or more random characters.

A couple of things to keep in mind while you’re using pipelines. The first is don’t overdo it. If my command becomes too long I tend to just stop using more pipelines because the whole thing becomes unreadable. So whenever I tend to use too many pipelines I save the output in a variable and continue on the next line with that variable at a logical point. An alternative to this is to use the backtick (`) character. Which is found on the top left on most keyboards. Example:

With the above example I do use tab indentation to keep stuff as readable as possible it identifies commands that belong together in this case.

That’s it for now, subscribe if you want to keep following my blog 🙂

PowerShell 1XX post series

  1. PowerShell 101 – The absolute basics
  2. PowerShell 102 – Practice scripts
  3. PowerShell 103 – Pipelines (current)
  4. PowerShell 104 – Operators

2 thoughts on “PowerShell 103 – Pipelines

Leave a Reply