Directory Size Through FileSystemObject

The following code snippet to get the directory size of different folders in a local or remote computer. However for some folders (like Windows or Windows.old) it is not calculating the size properly. For other folders it is calculating properly. By properly I mean that comparing the results with Windows Explorer.

$FileSysObj = New-Object -comobject Scripting.FileSystemObject
$FileSysObj.GetFolder[‘c:\windows.old’].Size
Remove-Variable FileSysObj

What can be wrong? I have searched and searched and searched. But no clue.

I’m not sure why that doesn’t work. For folders where you encounter an access denied, you can just use this approach instead.

$FileSysObj.GetFolder('c:\windows').SubFolders | % { $sum += $_.Size}; $sum

You’re just going to iterate through the .SubFolders property and then select each $FileSysObj.GetFolder.Size property from there and add it to $sum, finally displaying $sum at the end.

You can’t delete Windows.old that way. Too many files and folders have TrustedInstaller as the owner. The best way is to use the DiskCleanup tool and check for System files. If you don’t have a GUI, you can try a PowerShell function I wrote to be used on server core installations. http://jdhitsolutions.com/blog/2013/10/out-with-the-windows-old/

Looking at some quick tests

£> $FileSysObj = New-Object -comobject Scripting.FileSystemObject
£> $FileSysObj.GetFolder(‘C:\source’).Size
41898555590
£> $FileSysObj.GetFolder(‘C:\Windows’).Size
£> $FileSysObj.GetFolder(“C:\Windows”).Size
£> $FileSysObj.GetFolder(‘C:\Windows\Fonts’).Size
528986695
£> $FileSysObj.GetFolder(‘C:\Windows\System32’).Size
£> $FileSysObj.GetFolder(‘C:\Windows\System32\WindowsPowerShell’).Size
41881437

So whats different about those folders?

I think its permission based in that using the COm object you don’t get permissions to list the folder contents and therefore get the size. Also some folders will deny access which could well cause the COM object to stop counting. Think you’ll have to look at those folders another way as suggested above. You may want to just use a pure powershell approach:
Get-ChildItem -Path c:\windows -Recurse -File -Force | Measure-Object -Sum Length

Oops, looks like I jumped the gun. Sorry you just want a size, most people want to make it go away.

Thanks for your response. Get-ChildItem -Path c:\windows -Recurse -File -Force | Measure-Object -Sum Length works but is very slow.