PowerShell Get Size of Folders

This week another server hit low disk space on the C drive, so I decided it would be an appropriate time to work out a new PowerShell script. I wanted to calculate the size of each folder to determine the biggest threats and work down from there. Clean out the big stuff first kind of thing. If you have ever tried to do this via the Windows GUI, you know this can take awhile. Right-click -> Properties works great for calculating one folder’s size, but when you need to check 100, it’s a teeny bit tedious.

I decided to write a script from scratch to test/improve my scripting skills, but I did use the internet in the end for some formatting help on the Size In Megabytes conversion.

Note: If you find that your folder size is not correct, the most likely issue is that you need to include a -Force parameter on Get-ChildItem within the ForEach loop. This will force hidden items to be counted, and should accurately display the total file size. Example below.

$Items = (Get-ChildItem $Folder -Force -Recurse | 
  Measure-Object -Property Length -Sum)

Further Note: If you attempt to use the above fix, you could encounter a length error as shown below.

GetChildItem-ForceError

The file name must be less than 260 characters; the directory must be less than 248 characters.

The only viable fix I have found for this requires using cmdshell syntax rather than PowerShell. It’s a lot uglier to work with, and frankly, I got the information I needed without looking at system hidden files (it’s not like I was going to delete those anyways). Knowing how big the files were that I could delete was enough for me in this exercise. But if you really want the full answer…

-Force Error Workaround Using CMD
You can replace Get-ChildItem with the below in an attempt to work around hidden items. You’ll have to mess with the code a bit, but you wanted some homework, right?
My opinion though, just don’t worry about counting the hidden items. Save yourself the frustration.

CMD /c DIR C:\USERS /-c

Full script (Not using -Force or CMD)

## SET COMPUTER(S) TO CALCULATE FOLDER SIZES
$Computers = "COMPUTERNAME"
Invoke-Command -ComputerName $Computers -ScriptBlock {
## SET THIS VALUE FOR THE FOLDER TO RECURSE THROUGH
$FolderPath = 'C:\Users'

$Result = @() #Initializes the result array
#this populates the folder list
$Folders = (Get-ChildItem $FolderPath).FullName
ForEach ( $Folder in $Folders )
{
$Items = 0 #resets file size count on each folder
$Items = (Get-ChildItem $Folder -Recurse | 
  Measure-Object -Property Length -Sum)
$Result += [PSCustomObject] @{
  FolderPath = $Folder
  Size = $Items.Sum
  SizeInMB = "{0:N2}" -f ($Items.Sum / 1MB)
}#EndCustomObject
}#EndForEach
$Result | Sort Size -Descending |
  FT FolderPath,SizeInMb -AutoSize
}#EndInvoke
Advertisements