1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Powershell】フォルダの容量を取得する

Posted at

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)に出力します
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?