Sunday, April 17, 2016

Everyday Powershell - Part 40 - Get folder size

So my daughter (10 months) and I were hanging out on the couch listening to Pandora. I encourage her to play with the media center keyboard and she was doing that with gusto. When WHAM! Media Center PC hangs and when it reboots is unable to start the operating system.

We did a full power cycle and it came back fine, but reported low disk space. So it looks like my little girl hit her first problem with a full disk and windows hibernation. I'm so proud!

Her spamming had apparently asked the computer to hibernate. It tried but ran out of disk. So after getting back into the OS we needed to do a bit of a review and free up some space. At this point it dawned on us what our next part of Everyday Powershell was going to be about!

function get-foldersizes{
    param($startFolder )

    $report = @()

    $count = 0
    $colItems = ((Get-ChildItem $startFolder ) + (Get-ChildItem $startFolder -Hidden))
    foreach ($i in $colItems){
        write-progress -activity "Coutin Files" -Status $i.fullname -percentcomplete (($count / $colitems.count) * 100)
        if($i.PSIsContainer){
            $subFolderItems = (Get-ChildItem $i.FullName -File -Recurse | Measure-Object -property length -sum)
        }
        else{
            $subFolderItems = $i.FullName | Measure-Object -property length -sum
        }
        $temp = "" | select folder, size
        $temp.folder = $i.FullName
        $temp.size = [math]::round(($subFolderItems.sum / 1MB),2)
        $report += $temp
        $count++
    }
    $report | sort size
}

Super simple function that gets the size of all folders in $startfolder if that's null it just grabs the current folder.

So once the function was up and running my girl and I found an old copy of marvel heroes taking up 11gb. We deleted that and got back to the important business of playing with blocks!

Reference - We used this technet article as the basis for our script.