Google AIであるGeminiを使って未整理のフォルダのファイルを種類別にフォルダに分類するスクリプトを作成してみました。
古いHDDの大掃除が完了!✨ 中身がごちゃごちゃで手付かずでしたが、Geminiに『ファイルを種類別に仕分けるスクリプト作って!』とお願いしたら、一瞬で解決しました。
ExcelはExcelフォルダ、画像は画像フォルダへ自動で仕分けてくれるので、要らないファイルを見つけるのがすごく楽に! これ、月別整理や重複ファイル削除にも応用できそう。AI活用、すごい便利! #データ整理 #Gemini #PowerShell
次のコードはPowerShellで動作します。(ファイルは 拡張子.ps1で保存してください。UTF-8のBOM付で保存します。)wordや、excel、動画やパワーポイントのフォルダーに分類してファイルを移動します。
# 1. 基本設定
# スクリプトを置いた場所を基準に動作します
$basePath = Get-Location
$sourceFolderName = "整理したいファイルのフォルダを指定"
$sourceFolderPath = Join-Path $basePath $sourceFolderName
# 移動先のフォルダ名を定義します (フォルダ名は自由に変更できます)
$destFolders = @{
excel = @(".xlsx", ".xls", ".xlsm", "csv")
movie = @(".mp4", ".mov", ".avi", ".wmv", ".mkv")
picture = @(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".heic", ".raw") # "picuture"を"picture"に修正しました
pdf = @(".pdf")
powerpoint = @(".pptx", ".ppt")
word = @(".docx", ".doc")
etc = "その他" # ここで定義されていない拡張子のファイルが移動されるフォルダ
}
# 2. 移動先フォルダの作成
# 定義したフォルダが存在しない場合に作成します
Write-Host "--- フォルダの準備 ---" -ForegroundColor Yellow
foreach ($folder in $destFolders.Keys) {
$path = Join-Path $basePath $folder
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path
Write-Host "作成しました: $path"
}
}
# 3. ファイルの移動処理
Write-Host "`n--- ファイルの移動を開始します ---" -ForegroundColor Yellow
# サブフォルダ内もすべて検索 (-Recurse) し、ファイルのみを対象 (-File)
$files = Get-ChildItem -Path $sourceFolderPath -Recurse -File
foreach ($file in $files) {
$extension = $file.Extension.ToLower()
$moved = $false
# 各カテゴリの拡張子に一致するかチェック
foreach ($category in $destFolders.Keys) {
if ($category -ne "etc" -and $destFolders[$category] -contains $extension) {
$destinationFolder = Join-Path $basePath $category
$moved = $true
break # 一致したらループを抜ける
}
}
# どのカテゴリにも一致しなかった場合、etcフォルダに設定
if (-not $moved) {
$destinationFolder = Join-Path $basePath "etc"
}
# 移動先でのファイルパスを決定 (同名ファイル対策)
$destinationFile = Join-Path $destinationFolder $file.Name
$counter = 1
# もし移動先に同名のファイルが存在したら、ファイル名に番号を付けて重複を回避
while (Test-Path $destinationFile) {
$newName = "{0}_{1}{2}" -f $file.BaseName, $counter, $file.Extension
$destinationFile = Join-Path $destinationFolder $newName
$counter++
}
# ファイルを移動
try {
Move-Item -Path $file.FullName -Destination $destinationFile -ErrorAction Stop
Write-Host "移動: $($file.Name) -> $($destinationFolder)" -ForegroundColor Green
}
catch {
Write-Host "エラー: $($file.FullName) の移動に失敗しました。" -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
# 4. 空になったサブフォルダの削除 (任意)
# 下記のコメントアウトを解除すると、ファイルがなくなった後の空のフォルダをすべて削除します
# Get-ChildItem -Path $sourceFolderPath -Recurse -Directory | Where-Object { (Get-ChildItem -Path $_.FullName -Recurse -File).Count -eq 0 } | Remove-Item -Recurse -Force
# Write-Host "`n--- 空のフォルダを削除しました ---" -ForegroundColor Yellow
Write-Host "`n--- すべての処理が完了しました ---" -ForegroundColor Yellow
Geminiを使うと瞬時に便利なスクリプトを作成してくれるので大変便利です。
次のフォルダーに分類されます。

#GEMINI #PowerShell #AI