5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【powershell】MS Word を高速で横断検索する

Last updated at Posted at 2019-09-28

MS Word 内部テキストの高速抽出正規表現によるマッチ箇所の強調表示 を組み合わせて、.docx ファイルに対する grep 検索のようなものを作ってみました。

Select-ObjectWhere-Object による柔軟なフィルタリングと組み合わせることでいろいろな活用方法が考えられそうです。

コード

事前準備として、上記記事で紹介した Get-TextOfDocxDocumenthilight$profile に記入するかドットソースを使うなどして読み込んでおきます。

function Invoke-GrepOnDocx {
    <#
        .SYNOPSIS
        docx に対するGrep
        ・パイプライン経由での入力にのみ対応
        ・docx 以外は自動で無視する
        .PARAMETER pattern
        検索パターン
        .PARAMETER case
        指定時は大文字小文字を区別
        .EXAMPLE
        ls | Invoke-GrepOnDocx "ほげ"
    #>
    param (
        [string]$pattern,
        [switch]$case
    )
    $input | Where-Object Extension -eq ".docx" | ForEach-Object {
        $fileName = $_.Name
        $docxContent = Get-TextOfDocxDocumant -path $_.Fullname
        if ($docxContent.Status -eq "FILEOPENED") {
            Write-Error ("'{0}' is used by other process!" -f $fileName)
            return
        }
        $grep = $docxContent.Lines | Select-String -Pattern $pattern -AllMatches -CaseSensitive:$case
        foreach ($g in $grep) {
            "`n{0}:" -f $fileName | Write-Host -ForegroundColor DarkGray
            $g.Line | hilight -Pattern $pattern -case:$case -backgroundcolor "Yellow"
        }
        $total = $grep.Matches.Count
        if ($total) {
            "========== {0} ==========" -f $total | Write-Host -ForegroundColor Cyan
        }
    }
}

実行イメージ

20201117195535.png

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?