Friday Fun with Formatting

PowerShell is very adept at retrieving all sorts of information from computer systems in your network. Often the data is in a format that is hard to digest at a glance. For example, when you see a value like 1202716672 is that something in MB or GB? What if you need to view that value as KB? I don’t know about you but I’m not good at making those conversions in my head and on-the-fly. Instead, we often resort to commands like this.

That is much easier than seeing a value of 8589934592. The same thing applies when it comes to calculating percentages. Again, we’re back to using custom hashtables with Select-Object. Of course, you can go the extra mile and create custom format and type extensions. But sometimes, at least speaking for myself, you want something in between. So I created two functions, Format-Value and Format-Percent and packaged them as a module.

Format-Value will take any value and by default round it to an integer. Or you can specify to format the value as a certain unit of measurement such as GB or MB. You can even specify the number of decimal places. Or, you can use the -Autodetect parameter and the function will make the best guess about the ‘size’ of your value. Use -Verbose if you want to know what unit it detects.

I did a similar thing with percentages. All you have to do is specify a value and a total and the function does the rest. Again, you can specify the number of decimal places. By default, the function writes a numeric value to the pipeline which I find makes it easier if you want to sort. But you can also specify to get a percentage as a string which will use the -f operator. The string will include the % symbol. I take an extra step to remove the space between the value and symbol.

With the function, my PowerShell expressions become a little easier to write.

In the code sample I’m using the function and parameter aliases. But I like the result.

Download extract it to your modules directory and you should be good to go. I’ve set the minimum PowerShell version to 3.0 although there’s nothing I can think of that would prevent these commands from working on v2. But I’d like to drive you to at least 3 anyway.

I hope you’ll let me know what you think and what other types of data formatting you’d like to see added to the module.

NOTE: An update has been posted at

One thought on “Friday Fun with Formatting

  1. Pingback: BPOTW 2014-05-30 | SQL Notes From The Underground

Comments are closed.