大量に格納されたファイルを拡張子ごとにフォルダ分けする、PowerShellのサンプルを紹介します。
開発環境などで大量のファイルが溜まってきたときに、ファイルを整理するときに便利です。(例えば*.error、*.warning、*.info別に分けたいなど)
仕様
フォルダに格納されたファイルを拡張子ごとに、サブフォルダに格納します。
実行イメージ
下記のファイルの例だと、xlsxファイルが1つ、txtファイルが4つ格納されています。

この場合、実行すると5つのファイルが、新規作成された年月日のフォルダ「xlsx」、「txt」へ割り振りされます。

ソースコード
ソースコードは下記のとおりです。
$currentPathは日付ごとにフォルダ分けしたいファイルが存在するパスです。
適当に変えてください。
拡張子ごとにフォルダ分け.ps1
$currentPath = "C:\temp\powershell\file\"
#作業フォルダ移動
Set-Location -Path $currentPath
#フォルダのファイル一覧取得
$items = Get-ChildItem * -File -include *.log
#ファイルごとにループ
foreach ($item in $items) {
#ログファイル名
$currentName = $item.Name
#圧縮ファイル名
$archiveName = $currentName.Substring(0, $currentName.LastIndexOf('.')) + ".zip"
#既存ファイル有無確認
if (Test-Path $archiveName) {
Write-Output "圧縮ファイルが既に存在します:" + $archiveName
}else{
#ファイル圧縮
Compress-Archive -Path $currentName -DestinationPath $archiveName -ErrorAction Stop
Write-Output "圧縮しました:" + $archiveName
#ログファイル削除
Remove-Item $currentName -ErrorAction Stop
}
}
Read-Host
実行手順
では実行してみましょう。
先ほどのソースコードを、拡張子*.ps1として保存し実行します。
実行は右クリックメニュー「PowerShellで実行」で実行します。

実行すると下記のような画面が出るので、そのままエンターキーを押下でよいです。

実行前
実行前はフォルダがなく、ファイルのみが置かれたフォルダ構成です。

実行後
実行後は拡張子ごとにフォルダが作成され、ファイルがフォルダに格納されています。

フォルダの中はどうでしょうか?
txtフォルダ

xlsxフォルダ

参考情報
環境
下記の環境で作成・実行しております。
No. | 環境 | バージョン |
---|---|---|
1 | OS | Windows10 |
2 | PowerShell | 5.1 |
以上です。