How to get folder sizes | Powershell

Environment
  • Powershell


Content
The monitor was continuously warning us that one drive was no space. Needed a way to notice colleagues., and this PowerShell to be a helper:
$startFolder = "D:\TeamAShares"
$colItems = (Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object)

$totalSize = 0

#Folder size on $startFolder
foreach ($i in $colItems) {
   $subFolder = (Get-ChildItem ("$startFolder\" + $i.Name) -recurse -force | Measure-Object -property length -sum).Sum
   $totalSize += $subFolder
   $i.FullName + ": " + " {0:n2}" -f ($subFolder/ 1GB) + " GB"
}

#File size on $startFolder
$colItems = (Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $false} | Sort-Object)

if ($colItems.count -gt 0) {
   foreach ($i in $colItems) {
      $subFolder = (Get-Item ("$startFolder\" + $i.Name) -force | Measure-Object -property length -sum).Sum
      $totalSize += $subFolder
      $i.FullName + ": " + " {0:n2}" -f ($subFolder/ 1GB) + " GB"
   }
}

$startFolder + ": " + " {0:n2}" -f ($totalSize/ 1GB) + " GB"


References


Update