In the previous tip we introduced the Get-DisplayFileSize function which automatically converts bytes to readable numbers with units such as “KB” and “MB”.

Using Select-Object, you can now produce folder listings with meaningful file sizes:

$Length = @{
    Name = "Length"
    Expression = { 
    if ($_.PSIsContainer) { return }
    $Number = $_.Length
    $newNumber = $Number
    $unit = 'Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
    $i = 0
    while ($newNumber -ge 1KB -and $i -lt $unit.Length)
    {
        $newNumber /= 1KB
        $i++
    }
   
    if ($i -eq $null) { $decimals = 0 } else { $decimals = 2 }
    $displayText = "'{0,10:N$decimals} {1}'" -f $newNumber, $unit[$i]
    $Number = $Number | Add-Member -MemberType ScriptMethod -Name ToString -Value ([Scriptblock]::Create($displayText)) -Force -PassThru
    return $Number
    
    
     }
}
 
 
# pretty file sizes
dir $env:windir |
  Select-Object -Property Mode, LastWriteTime, $Length, Name |
  Sort-Object -Property Length

Note how the calculated property “Length” can still be sorted. It remains a byte value. Just the display text was changed.

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this year’s PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu.

Twitter This Tip! ReTweet this Tip!

Anonymous