PowerShell – Getting the size of all files within a folder tree

Last weekend I’ve been asked to write a script that will output the size of all files within a folder, and the files in all its sub-folders.
So, again something that’s possible with a one-liner Smile

Get-ChildItem D:\Software -recurse | Select-Object Name, @{Name=”KiloBytes”;Expression={$_.Length / 1KB}}

You don’t want the output to be in Kb but in MB? No problem…

Get-ChildItem D:\Software -recurse | Select-Object Name, @{Name=”MegaBytes”;Expression={$_.Length / 1MB}}


  1. You can create script blocks for KB and MB ahead of time

    Then use them as you need depending on the folder: dir c:files | select fullname, $mb

    or even format the number

    $mb=@{Name=”MB”;Expression={“{0:F2}” -f ($_.length/1MB)}}

  2. Jeff Wouters says:

    Script blocks are definitely the way to go when you’re building a script since you can use them multiple times later in the script, but for a one-liner I can’t think of a reason to use it… or am I forgetting something?

  3. I was merely suggesting defining scriptblocks so you could reuse them in other one liners. Suppose you want to check a diffierent folder and you want this to be in MB, just the the MB scriptblock in the select statement. I’m just trying to save some typing.

  4. Jeff Wouters says:

    Then we are in agreement 🙂 Your feedback and tips are always welcome btw…

  5. Arun says:

    Jeff : if you dont mind can you just give some brief about this line @{Name=”MegaBytes”;Expression={$_.Length / 1MB}} is this supposed to be a hash table ? am not understanding how this works

  6. Jeff Wouters says:

    Hi Arun,

    What happens there is that I’ve created a custom property with the name “MegaBytes” and expression (value) of the length of the file and devide that by 1MB so that it will provide an output in the MB size.

    This is a custom property, not a hash table since that doesn’t allow you to customize the property name for example: http://technet.microsoft.com/en-us/library/ee692803.aspx

    Does that anwser your question?


Leave a Reply

Your email address will not be published. Required fields are marked *