Changing Units

by Nov 16, 2011

When you list folder contents, file sizes are in bytes. If you'd rather like to view them in MB or GB, you can use calculated properties, but by turning numbers into MB or GB, you turn them into text strings. That's bad because then you can no longer sort them or filter them based on size.

A better approach overrides the display function ToString() only. This way, the file size stays numeric but displays any way you like:

PS> dir $env:windir | Select-Object Mode, LastWriteTime, Length, Name | ForEach-Object { 
if
($_.Length -ne $null) { $_.Length = $_.Length | Add-Member ScriptMethod ToString {
(
'{0:0.0} KB' -f ($this/1KB)) } -Force -pass } $_} | Sort-Object Length

Twitter This Tip!
ReTweet this Tip!