Powershell script to check folder size
When we run into “low disk space” error, we will need to figure out what folder or file causes the error. By default, Windows only show file size not folder size. We sometime have to click through the folders to find the “culprit.
I developed the below PS script to help smooth this process. What it does is to do a recurse scan of each sub folders inside target folder and calculate the total length of the files and write a report in excel.
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "Target Folder"
$c.Cells.Item(1,3) = "Max File Name"
$c.Cells.Item(1,4) = "Max File Sizem"
$c.Cells.Item(1,5) = "Folder Name"
$c.Cells.Item(1,6) = "Folder Size(MB)"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$intRow = 2
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$intRow = 2
# Inputbox
$x = new-object -comobject MSScriptControl.ScriptControl
$x.language = "vbscript"
$x.addcode("function getInput() getInput = inputbox(`"Enter Your Computer Name`",`"Computer Name`") end function" )
$Computer = $x.eval("getInput")
$c.Cells.Item($intRow,1) = $Computer.ToUpper()
$y = new-object -comobject MSScriptControl.ScriptControl
$y.language = "vbscript"
$y.addcode("function getInput() getInput = inputbox(`"Enter The Target Drive or Folder Name`",`"Folder Name`") end function" )
$TargetFolder = $y.eval("getInput")
$c.Cells.Item($intRow,2) = $TargetFolder.ToUpper()
$args = "\\$computer\$TargetFolder\"
$items = get-childitem $args | sort length -desc
$MaxFile = $items[0]
$c.Cells.Item($intRow,3) = $MaxFile.name
if ($MaxFile.length/1MB -ge 1024)
{$c.Cells.Item($intRow,4).Interior.ColorIndex = 3
$c.Cells.Item($intRow,4) = "{0:N0}" -f ($MaxFile.length/1MB)}
Else
{$c.Cells.Item($intRow,4) = "{0:N0}" -f ($MaxFile.length/1MB)}
$folders = $items | where{$_ -is [system.IO.directoryInfo]}
foreach ($folder in $folders)
{
$files = get-childitem ([String]$args + $folder.name) -include *.* -recurse -force
$foldersize=0
foreach ($f in $files) {$foldersize+=$f.length}
$c.Cells.Item($intRow,5) = $Folder.name
if ($foldersize/1MB -ge 1024)
{$c.Cells.Item($intRow,6).Interior.ColorIndex = 3
$c.Cells.Item($intRow,6) = "{0:N0}" -f ($foldersize/1MB)}
Else
{$c.Cells.Item($intRow,6) = "{0:N0}" -f ($foldersize/1MB)}
$intRow = $intRow + 1
}
$d.EntireColumn.AutoFit()