Display directory structure with size in Powershell

前端 未结 1 1251
情书的邮戳
情书的邮戳 2021-02-06 13:05

Trying to have \"dir\" command that displays size of the sub folders and files. After googling \"powershell directory size\", I found thew two useful links

  1. Determi
相关标签:
1条回答
  • 2021-02-06 13:21

    The first minor mod would be to avoid creating a new FileSystemObject for every directory. Make this a function and pull the new-object out of the pipeline.

    function DirWithSize($path=$pwd)
    {
        $fso = New-Object -com  Scripting.FileSystemObject
        Get-ChildItem | Format-Table  -AutoSize Mode, LastWriteTime, Name, 
                        @{ Label="Length"; alignment="Left"; Expression={  
                             if($_.PSIsContainer)  
                                 {$fso.GetFolder( $_.FullName).Size}   
                             else  
                                 {$_.Length}  
                             } 
                         }
    }
    

    If you want to avoid COM altogether you could compute the dir sizes using just PowerShell like this:

    function DirWithSize($path=$pwd)
    {
        Get-ChildItem $path | 
            Foreach {if (!$_.PSIsContainer) {$_} `
                     else {
                         $size=0; `
                         Get-ChildItem $_ -r | Foreach {$size += $_.Length}; `
                         Add-Member NoteProperty Length $size -Inp $_ -PassThru `
                     }} |
            Format-Table Mode, LastWriteTime, Name, Length -Auto
    }
    
    0 讨论(0)
提交回复
热议问题