Let's put what you've learned so far into practice using PowerShell's pipeline with objects.
- By Jeffery Hicks
We've covered a lot in the last few weeks, so now it's time to put some of what you've been learning to work in a relatively practical example. How about we try to figure out how much space files in %TEMP% are consuming?
First, you need to figure out what directory %TEMP% refers to. You can use the variable environmental PSDrive to return the directory by using $env:temp. Once you have that, a directory listing is the first step:
PS C:\> dir $env:temp -recurse
This lists the files and subfolders. The next step is to add up all of the file sizes. In other shells and languages, this may have meant parsing the directory output or keeping a running total going as each file was processed.
But in PowerShell, you're working with file objects, which have a length property that indicates their size. PowerShell also has a cmdlet that can do the measuring for you called, naturally, Measure-Object. In this example, you'll give it a property to measure and a parameter indicating that you want to calculate a sum based on that property:
PS C:\> dir $env:temp -rec | measure-object -property length -sum
Count : 26
Sum : 3192605
Property : length
That's not too bad and certainly helpful. But let's keep going. Measure-Object wrote an object to the pipeline with properties of Count, Average, Sum, Maximum and Minimum. If you only want to see the Sum property, you can refine your expression like this:
PS C:\> (dir $env:temp -rec | measure-object length -sum).sum
By enclosing the expression in parentheses, you're telling PowerShell to treat it as a single expression. This, in essence, is the object returned by Measure-Object, and all you need is the sum property. However, this value is in bytes. Maybe you want it in megabytes. That's simple -- divide by 1MB:
PS C:\> (dir $env:temp -rec | measure-object length -sum).sum/1mb
Finally, you may want to format that number. There are several ways to do that, but the easiest is to simply round the value to an integer by telling PowerShell to treat the entire value as type [int]:
PS C:\> (dir $env:temp -rec | measure-object length -sum).sum/1mb -as [int]
With one relatively simple line of PowerShell that leverages the pipeline and objects, you get a short and sweet answer.
Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.