ankit
ankit

Reputation: 1

check folder and sub-folder sizes

I am kind of new to PowerShell. When my disk gets full several times and I have to clean it manually. I tried to create a PowerShell script which can tell me which folder is consuming more than 10gb with its location.

I used this -

$Directory = 'C:' 
$FilesAndFolders =Get-ChildItem -Path $Directory -Recurse -ErrorAction SilentlyContinue -Depth 2 
Foreach ($FileOrFolder in $FilesAndFolders) { 
    if ($FileOrFolder.Attributes -contains "Directory") { 
        #This is a folder - calculate the total folder size 
        $Length = (Get-ChildItem $FileOrFolder.FullName -Recurse | 
            Where-Object {$_.Attributes -notcontains "Directory"} | 
                Measure-Object -Sum -Property Length).Sum 
        $FileOrFolder | Select-Object Name, FullName, @{Name="Length"; Expression={$Length}} 
    } 
}

Upvotes: 0

Views: 1611

Answers (2)

js2010
js2010

Reputation: 27428

I have similar things here. 'dus' outputs folders under the current directory sorted by size, and 'siz' outputs files. Then you can cd down a folder and run them again. It's based on unix aliases I used to have. I put them in my $profile.

function com { param([Parameter(ValueFromPipeline=$True)]
  [int64]$number)
  process { '{0:n0}' -f $number } }

function dus($dir=".") { 
  get-childitem -force -directory $dir -erroraction silentlycontinue -attributes !reparsepoint | 
    foreach { $f = $_ 
      get-childitem -force -r $_.FullName  -attributes !reparsepoint -ea 0 | 
        measure-object -property length -sum -erroraction silentlycontinue | 
        select @{Name="Name";Expression={$f}},Sum} | sort Sum |
    select name,@{n='Sum';e={$_.sum | com}}
}

function siz() {
  ls -file -force | select name,length | 
    sort length |
    select name,@{n='Length';e={$_.length | com}}
}

Upvotes: 0

Gopa
Gopa

Reputation: 354

Your current code gives you bytes. You have to do a (Get-ChildItem C:\Directory | Measure-Object -Property Length -sum) /1Gb to convert the value to GB. Also - Force to look for hidden or system files

Upvotes: 1

Related Questions