7CF Style Tokyo

1999, つまり世紀末マインドで気ままにWEB技術で遊ぼうというコンセプトです

ローカルディレクトリ内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"

ライター

HARLYA

無能アリ

趣味でフルスタック開発をしている。巨人の肩に乗りまくりで四捨五入すればエンドユーザー。

関連記事

PythonでPDFにmp3をバインドする

更新日: 2026/03/28

データ処理

ブラウザの音声入力インターフェース(VUI)を試す

更新日: 2026/03/28

WEB
データ処理

Turf.jsを使ったマップグリッド配置とセルごとのステータス管理

更新日: 2026/03/28

WEB
データ処理