PowerShellでフォルダ容量調査スクリプト

Cドライブの容量がパンパンになったときにどのフォルダーが容量を食っているか調査するスクリプト。

実装

以下を check-folder-size.ps1 として保存する。

# フォルダサイズ調査スクリプト
# 例:.\check-folder-size.ps1 -Path "C:\"

param(
    [string]$Path = "C:\",
    [switch]$ExportCsv,
    [string]$OutputDir = "$env:USERPROFILE\Desktop"
)

# パス確認
if (-not (Test-Path $Path)) {
    Write-Host "エラー:パスが存在しません:$Path" -ForegroundColor Red
    exit 1
}

Write-Host "調査対象:$Path" -ForegroundColor Cyan
$startTime = Get-Date

$results = Get-ChildItem $Path -Directory -Force -ErrorAction SilentlyContinue |
    ForEach-Object {
        Write-Host "対象:$($_.Name)..." -ForegroundColor Yellow -NoNewline

        $size = (Get-ChildItem $_.FullName -Recurse -File -Force -ErrorAction SilentlyContinue |
            Measure-Object -Property Length -Sum).Sum

        $sizeGB = if ($size) {
            [math]::Round($size / 1GB, 2)
        } else {
            0
        }

        Write-Host " → $sizeGB GB" -ForegroundColor Green

        [PSCustomObject]@{
            Folder   = $_.Name
            FullPath = $_.FullName
            SizeGB   = $sizeGB
            SizeMB   = if ($size) {
                [math]::Round($size / 1MB, 2)
            } else {
                0
            }
        }
    } |
    Sort-Object SizeGB -Descending

# CSV出力
if ($ExportCsv) {
    $folderName = (Split-Path $Path -Leaf) -replace '[:\\\/]', '_'

    if ([string]::IsNullOrEmpty($folderName)) {
        $folderName = "Root"
    }

    $outputPath = Join-Path $OutputDir "FolderSize_$($folderName)_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"

    $results |
        Export-Csv -NoTypeInformation -Path $outputPath -Encoding UTF8

    Write-Host "CSV: $outputPath" -ForegroundColor Green
}

$totalTime = ((Get-Date) - $startTime).TotalMinutes

Write-Host ""
Write-Host "所要時間:$($totalTime.ToString('F1')) 分" -ForegroundColor Cyan

$results | Format-Table -AutoSize

実行方法

以下で実行する。
-Path に調査したい任意のパスを指定する。

.\check-folder-size.ps1 -Path "C:\Users"

コメント

タイトルとURLをコピーしました