Directory Size Through FileSystemObject

This topic contains 5 replies, has 4 voices, and was last updated by  Malik Amaduddin 3 years, 7 months ago.

  • Author
  • #21076

    Malik Amaduddin

    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
    Remove-Variable FileSysObj

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

  • #21082

    Stephen Owen

    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.

  • #21083

    Jeffery Hicks

    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.

  • #21086

    Richard Siddaway

    Looking at some quick tests

    £> $FileSysObj = New-Object -comobject Scripting.FileSystemObject
    £> $FileSysObj.GetFolder('C:\source').Size
    £> $FileSysObj.GetFolder('C:\Windows').Size
    £> $FileSysObj.GetFolder("C:\Windows").Size
    £> $FileSysObj.GetFolder('C:\Windows\Fonts').Size
    £> $FileSysObj.GetFolder('C:\Windows\System32').Size
    £> $FileSysObj.GetFolder('C:\Windows\System32\WindowsPowerShell').Size

    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

    • #21152

      Malik Amaduddin

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

  • #21090

    Jeffery Hicks

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

You must be logged in to reply to this topic.