ExcelKeywordFinder.ps1
# 事前設定
$scriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
# 検索ディレクトリ
$searchDir = "D:\Dropbox\01.ビジネス"
Write-Host "検索ディレクトリ: $searchDir"
# 検索キーワード
$keyword = "1"
Write-Host "検索キーワード: $keyword"
# 除外するディレクトリのリスト
$excludeDirs = @(
"D:\Dropbox\01.ビジネス\ExcludeDir1",
"D:\Dropbox\01.ビジネス\ExcludeDir2"
)
Write-Host "除外するディレクトリ: $($excludeDirs -join ', ')"
# 結果を保存するファイル名に現在の日時を追加
$currentDateTime = Get-Date -Format "yyyyMMddHHmmss"
$resultFileName = "ExcelKeywordFinder_$currentDateTime.xlsx"
$resultFile = Join-Path -Path $scriptPath -ChildPath $resultFileName
Write-Host "結果ファイル: $resultFileName"
# メイン
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
if (Test-Path $resultFile) {
$resultWorkbook = $excel.Workbooks.Open($resultFile, $null, $true)
Write-Host "既存の結果ファイルを開きます: $resultFileName"
} else {
$resultWorkbook = $excel.Workbooks.Add()
$resultWorkbook.SaveAs($resultFile)
Write-Host "新しい結果ファイルを作成します: $resultFileName"
}
$resultSheet = $resultWorkbook.Sheets.Item(1)
$rowIndex = $resultSheet.UsedRange.Rows.Count + 1
# ファイルの検索と処理
Get-ChildItem -Path $searchDir -Include "*.xlsx", "*.xls", "*.xlsm" -Recurse | Where-Object {
$exclude = $false
foreach ($excludeDir in $excludeDirs) {
if ($_.FullName.StartsWith($excludeDir)) {
$exclude = $true
break
}
}
-not $exclude
} | ForEach-Object {
$filePath = $_.FullName
Write-Host "処理するファイル: $filePath"
try {
$workbook = $excel.Workbooks.Open($filePath, $null, $true)
foreach ($worksheet in $workbook.Worksheets) {
$found = $worksheet.UsedRange.Find($keyword)
if ($found) {
$cellAddress = $found.Address($false, $false, 1, $false)
$matchedValue = $found.Text
$resultSheet.Cells.Item($rowIndex, 1).Value2 = $filePath
$resultSheet.Cells.Item($rowIndex, 2).Value2 = $cellAddress
$resultSheet.Cells.Item($rowIndex, 3).Value2 = $matchedValue
$rowIndex++
$resultWorkbook.Save()
Write-Host " 一致が見つかりました: セル $cellAddress, 内容 '$matchedValue'"
}
}
$workbook.Close($false)
} catch {
Write-Host " エラーが発生しました: $_"
}
}
$resultWorkbook.Close($false)
$excel.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
Write-Host "検索が完了しました。結果は $resultFile に保存されました。"
Write-Host "Enterキーを押して終了してください..."
$null = Read-Host