windowspowershelldirectory-structureget-childitem

Remote Directories with sizes


I want to import a csv list of file servers and shares ...

"\fileserver1\share"

"\fileserver2\share"

"\fileserver3\share"

Then export only the top-level directory path (UNC) with the size in MB of the entire directory and sub directories on a single line and get any errors that are thrown also exported to the CSV. I do get multiple "Get-ChildItem : The specified path, file name, or both are too long." errors and need the path...

FolderName FolderSizeMB

"\fileserver1\share" 1.19

"\fileserver2\share" 2.19

"\fileserver3\share" 3.19

I have manually run this script but it only gives the size for the top level and not the entire directory

$targetfolder = "\\fileserver\share"
gci $targetfolder -Directory -force -ea SilentlyContinue | % {
    $len = 0
    gci $_.fullname -Directory -force -ea SilentlyContinue | % { $len += $_.length }

    [PSCustomObject]@{
        FolderName   =  $_.fullname
        FolderSizeMB = '{0:N2}' -f ($len / 1MB)
    }
}

I have also tried this

Listing directories with name and size

But I am not able to get errors exported.


Solution

  • $targetfolder = "\\fileserver\share"
    Get-ChildItem $targetfolder -Directory -force -ErrorAction SilentlyContinue | foreach {
        $measure =
            Get-ChildItem $_.fullname -File -Recurse -force -ErrorAction SilentlyContinue -ErrorVariable err |
            measure -Property 'Length' -Sum 
    
        [PSCustomObject]@{
            FolderName   =  $_.fullname
            FolderSizeMB = ($measure.Sum / 1MB).ToString('N2')
            Errors = "$err"
        }
    } |
    Export-Csv -Path 'C:\Users\Admin\Documents\Report.csv' -NoTypeInformation