【AIによる概要】
# ==========================================
# 1. 設定
# ==========================================
# (1) 検索したいパスをここに並べてください
$searchRootList = @(
"C:\Path\To\Folder1",
"D:\Another\Path\Folder2"
)
# (2) 検索したいキーワードをここに並べてください(1つでも複数でもOK)
$searchKeywords = @(
"あいうえお",
"かきくけこ"
)
# 実行日の日付(例: 20260601)を取得し、ターゲットとなるフォルダ名を設定
$date = Get-Date -Format "yyyyMMdd"
$outputFile = ".\search_result_$date.txt"
# キーワード一覧を表示用にカンマ区切りにする
$keywordDisplay = $searchKeywords -join "」または「"
$headerText = "【検索結果】「$keywordDisplay」が含まれるファイル一覧(対象日: $date)"
# ==========================================
# 2. 処理開始
# ==========================================
# キーワードが空の場合は処理を中断
if ($searchKeywords.Count -eq 0) {
Write-Error "検索キーワードが指定されていません。"
exit
}
# 配列のキーワードを「OR」を意味する正規表現(パターン1|パターン2)に変換
$searchPattern = [string]::Join("|", ($searchKeywords | ForEach-Object { [regex]::Escape($_) }))
# 出力ファイルを初期化(UTF-8 でヘッダーを書き込み)
Set-Content -Path $outputFile -Value $headerText -Encoding utf8
$totalFolderCount = 0
# 指定された複数のパスを順番に処理
foreach ($searchRoot in $searchRootList) {
Write-Host "----------------------------------------"
Write-Host "ルートパスを探索中: $searchRoot"
if (-not (Test-Path $searchRoot)) {
Write-Warning "指定されたルートパスが見つからないためスキップします: $searchRoot"
continue
}
# 【ここを改修】指定ルート配下から「本日の日付($date)」と完全に一致するフォルダを【再帰的】にすべて取得
$dateFolders = Get-ChildItem -Path $searchRoot -Directory -Recurse |
Where-Object { $_.Name -eq $date }
if (-not $dateFolders) {
Write-Host "-> 本日の日付フォルダ($date)が見つかりませんでした。"
continue
}
Write-Host ("-> {0} 個の本日の日付フォルダが見つかりました。検索を開始します。" -f $dateFolders.Count)
$totalFolderCount += $dateFolders.Count
# 各日付フォルダをループ処理
foreach ($folder in $dateFolders) {
$targetFolder = $folder.FullName
Write-Host " 処理中: $targetFolder"
# 検索処理を実行し、結果を配列に格納
$matchedFiles = Get-ChildItem -Path $targetFolder -File |
Select-String -Pattern $searchPattern |
Group-Object Path | ForEach-Object { $_.Name }
# 各フォルダの結果を追記
Add-Content -Path $outputFile -Value "`n--- フォルダ: $targetFolder ---" -Encoding utf8
if ($matchedFiles) {
Add-Content -Path $outputFile -Value "対象のキーワードが見つかりました。" -Encoding utf8
$matchedFiles | Out-File -FilePath $outputFile -Encoding utf8 -Append
} else {
Add-Content -Path $outputFile -Value "対象ファイルはありませんでした。" -Encoding utf8
}
}
}
# 3. 【Shift-JISへの一括変換】と最終確認
if ($totalFolderCount -gt 0) {
$content = Get-Content -Path $outputFile -Raw
$sjisEncoding = [System.Text.Encoding]::GetEncoding("shift_jis")
[System.IO.File]::WriteAllText((Convert-Path $outputFile), $content, $sjisEncoding)
Write-Host "----------------------------------------"
Write-Host "すべての検索が完了し、Shift-JIS で保存しました。出力先: $outputFile"
} else {
Write-Warning "すべての指定パスにおいて、本日の日付フォルダ($date)が1つも見つかりませんでした。"
}
