LoginSignup
2
9

More than 5 years have passed since last update.

Powershellで各フォルダのサイズを調べて表示

Posted at

SSDの容量が少なくなってきたので整理のためにサイズの大きいフォルダを探したい

コマンド

こんな感じで出せるので末尾から見ていけば良さそうです。

dir | %{ new-object PSObject -property @{ name=$_.Name; size=(dir $_.Name -recurse | measure length -sum).sum } } | sort size

※エラー処理はしていないので空フォルダやアクセス権のないフォルダがあると色々出ますがそれは気にしないことにします。

ジャンクション対応

上のコマンドでだいたい問題無いのですが、整理の過程でジャンクションを使ってHDD逃したりしていたら正確にサイズが出せなくなったのでジャンクション無視版も作ってみました。

ジャンクションはReparsePointのフラグが立つようなのでその属性を持つディレクトリだけ無視して再帰的にサイズを求める関数を作ります。

function Get-DirectorySize {
  param([Parameter(ValueFromPipeline=$true)][System.IO.FileSystemInfo]$info)
  process {
    $length = 0
    if ($info.Attributes.HasFlag([System.IO.FileAttributes]::Directory)) {
      if (!$info.Attributes.HasFlag([System.IO.FileAttributes]::ReparsePoint)) {
        foreach ($d in ([System.IO.DirectoryInfo]$info).GetFileSystemInfos()) {
          $length += (Get-DirectorySize $d).size
        }
      }
    } else {
      $length = ([System.IO.FileInfo]$info).Length
    }
    new-object PSObject -property @{ name=$info.name; size=$length }
  }
}

後は呼ぶだけ

dir | Get-DirectorySize | sort size

※FileSystemInfoを受け取る関数にしてしまったので直接文字列を渡すと怒られます。

2
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
9