Get a Folder Size with PowerShell

Ad

It’s really easy to get the size of a folder with PowerShell. Even though the directory does not actually have a property for size, you just need to get the size of all of the files inside the folder.

function Get-FolderSize {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Path,
[ValidateSet("KB","MB","GB")]
$Units = "MB"
)
  if ( (Test-Path $Path) -and (Get-Item $Path).PSIsContainer ) {
    $Measure = Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum
    $Sum = $Measure.Sum / "1$Units"
    [PSCustomObject]@{
      "Path" = $Path
      "Size($Units)" = $Sum
    }
  }
}

One of my favorite things about this script is the ability to choose to get the folder size in KB, MB or GB.

 

This won’t include any results from items that you don’t have read access to, so be aware of that. Otherwise, it’s a fast and easy way to get the folder size from PowerShell!

Ad
Ad
Find Tech Jobs on Dice!
  • Skidrow Ray

    Great piece of code! kudos! +1

  • Anton VS

    How do I add this to powershell?

    • Michael Simmons

      Hi Anton,
      There are a couple of options to load it into PowerShell:

      – Copy/Paste the code into a PowerShell ISE window, and then run the code.
      – Save it as a function in another script, then call the function from other parts of the script
      – Save it as a .PS1 file and then call that file from other scripts or PowerShell sessions

      The important thing to remember is that as a function it will only load the command into your current session. After it’s loaded into PowerShell you can run the command by calling it like this:

      Get-FolderSize C:\Users\Michael\Desktop -Units “MB”