ローカルディレクトリ内WordファイルGrepスクリプト(PowerShell)
公開日: 2026/07/08 / 更新日: 2026/07/08
データ処理
$app = $null
$doc = $null
$target = $null
$searchDirectory = "C:\Users\YourName\Documents\Specs"
$searchKeyword = "要件定義"
try {
$app = New-Object -ComObject Word.Application
$app.Visible = $false
$app.DisplayAlerts = 0
$wordFiles = Get-ChildItem -Path $searchDirectory -Include "*.doc", "*.docx" -Recurse -File
Write-Host "検索を開始します..."
Write-Host "対象フォルダ: $searchDirectory"
Write-Host "検索キーワード: $searchKeyword"
Write-Host "対象ファイル数: $($wordFiles.Count) 件"
Write-Host "--------------------------------------------------"
foreach ($file in $wordFiles) {
try {
$doc = $app.Documents.Open($file.FullName, $false, $true)
$target = $doc.Content
if ($target.Text -match $searchKeyword) {
Write-Host "[発見] $($file.FullName)" -ForegroundColor Green
}
} catch {
Write-Host "[エラー] $($file.Name) の読み込みに失敗しました。" -ForegroundColor Yellow
} finally {
if ($null -ne $doc) {
$doc.Close($false)
}
if ($null -ne $target) { [System.Runtime.InteropServices.Marshal]::ReleaseComObject($target) | Out-Null }
if ($null -ne $doc) { [System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc) | Out-Null }
$target = $null
$doc = $null
}
}
Write-Host "--------------------------------------------------"
Write-Host "すべての検索が完了しました。"
} catch {
Write-Error "【致命的なエラー】処理を中断します。"
Write-Error "詳細: $_"
} finally {
if ($null -ne $app) {
$app.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($app) | Out-Null
}
$app = $null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
[System.GC]::Collect()
}powershell -NoProfile -ExecutionPolicy Bypass -File "C:\保存先パス\wordGrep.ps1"ライター
H
HARLYA
無能アリ
趣味でフルスタック開発をしている。巨人の肩に乗りまくりで四捨五入すればエンドユーザー。