5
5

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.

【Power Shell】フォルダサイズ取得スクリプトの作成

Last updated at Posted at 2022-06-15

コマンドプロンプトのdirコマンドでフォルダサイズを確認するような運用作業があり
毎回手打ちするのが嫌なので、スクリプトを作成しようと思いました。

dirコマンドを実行する際に、以下のパラメーターの指定を行っておりました。

/s 再帰的に処理する
/a 指定した属性のみ表示を行う。-はNotで、指定した属性以外の表示となる。

個人的にBatを作成するのが嫌で、PowerShellで作成する事としました。
Get-ChildItemコマンドを使用してフォルダサイズの取得を行おうと思います。

以下のパラメータを使用します。
※下記URLを参考に致しました。
https://docs.microsoft.com/ja-jp/powershell/module/Microsoft.PowerShell.Management/Get-ChildItem?view=powershell-7

-Recurce 再帰的に処理する
-Force 非表示の項目を取得(隠しファイル等)

Get-ChildItemコマンドを取得した情報の"Length"列にファイルサイズが出力されます。以下、実行イメージとなります。

Sample
Mode                 LastWriteTime         Length Name                                                                              
----                 -------------         ------ ----                                                                              
-a----        2022/06/15     21:04              0 test1.txt                                                                         
-a----        2022/06/15     21:04              0 test2.txt                                                                         
-a-h--        2022/06/15     21:05              4 test3.txt                                                                         
-a----        2022/06/15     21:05              8 test4.txt     
     

"Length"カラムの合計値の取得を行います。
Get-ChildItemコマンドで取得した情報を、Measure-Objectコマンドに渡して合計値の取得を行います。下記のコマンドで合計値が取得出来ます。

Get-ChildItem -Recurse -Force | Measure-Object -Sum Length

"Sum"行に出力された値が、フォルダサイズとなります。
"Count"行は、ファイル数となります。
以下、実行イメージとなります。

Sample_2
Count    : 4
Average  : 
Sum      : 12
Maximum  : 
Minimum  : 
Property : Length

※Measure-Objectコマンドの説明は詳しくないので、出来ないです。
下記URLが参考となりました。
凄くざっくり言うと、受け取った値の合計値や平均値等を計算してくれるコマンドだと思っています。今回は、Measure-Object -Sum Length で実行を行っていますが、-Sumから-Minに変更すると最小値の計算を行えます。便利です。
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/measure-object?view=powershell-7.2

フォルダサイズの取得まで行えました。
あとは、対象フォルダに移動する・ログに残す事を行うような機能があれば良いなと思ったので、最終的に下記のようなスクリプトを作成致しました、
以下、実行イメージとなります。

Sample.ps1
#フォルダサイズ取得対象
$Target_Dir = "C:\Users\Test_User\Desktop\test"
#時間の取得
$Get_Time = Get-Date -Format "yyyyMMdd_HHmmss"
#ログファイルの作成
$Log_File =  "C:\Users\Test_User\Desktop\Log\" + $Get_Time + ".log"

cd $Target_Dir

Get-ChildItem -Recurse -Force | Measure-Object -Sum Length > $Log_File

簡単なスクリプトとなりますが、参考になれば幸いです。

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?