WindowsのPowershellで、サブフォルダも含めたフォルダのサイズを調べたいとき。
指定されたフォルダパスのフォルダサイズを再帰的に取得し、その結果をファイルに出力します。
スクリプト
#容量を取得するフォルダパス
$filePath = "C:\"
#スクリプトのパス
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path
#スクリプトのパスに移動
cd $scriptRoot
"処理開始:" + (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")
#指定パスのフォルダサイズを再帰的に取得(サブフォルダも含む)
#取得結果はスクリプトパスに出力
Get-ChildItem $filePath `
| Sort LastWriteTime `
| Select-Object Name, LastWriteTime, @{ name = "Size"; expression = { `
[math]::round((Get-ChildItem $_.FullName -Recurse -Force `
| Measure-Object Length -Sum `
).Sum ) `
} } | Format-Table -AutoSize > FolderSize.txt
"処理終了:" + (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")
詳しい説明
容量を取得するフォルダパス
$filePath = "C:\"
C:\ ドライブのサイズを取得するためのフォルダパスを設定します。
取得したいフォルダパスをここで指定します。
スクリプトのパスを取得し、そのパスに移動
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path
cd $scriptRoot
スクリプトのパスを取得し、そのディレクトリに移動します。
タイムスタンプを表示
"処理開始:" + (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")
"処理終了:" + (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")
処理の開始時刻と終了時間を表示します。
指定パスのフォルダサイズを再帰的に取得
Get-ChildItem $filePath `
| Sort LastWriteTime `
| Select-Object Name, LastWriteTime, @{ name = "Size"; expression = { `
[math]::round((Get-ChildItem $_.FullName -Recurse -Force `
| Measure-Object Length -Sum `
).Sum ) `
} } | Format-Table -AutoSize > FolderSize.txt
-
Get-ChildItem
コマンドレットを使用して、指定されたパス($filePath)のフォルダとファイルを取得します - 取得したアイテムは
LastWriteTime
でソートします -
Select-Object
を使用して、フォルダ名 (Name)、最終更新日時 (LastWriteTime)、フォルダサイズ (Size) を選択します -
Size
は、フォルダ内のすべてのファイルのサイズの合計を再帰的に計算し、四捨五入しています - 最後に、これらの情報をテーブル形式
Format-Table
でファイル(FolderSize.txt)に出力します