<# : バッチコマンド(PowerShellコメント)開始
@echo off & setlocal
rem
rem  正規表現を用いたテキスト検索
rem
rem
rem     RegExS.bat  [正規表現] [検索対象フォルダー] [ファイル名のフィルター] 
rem                 [-e 文字コード種別] [-g グループ名/番号] 
rem                 [-h] [-i] [-n] [-r] [-s] [-x 除外フィルター]
rem                 [-bc マッチ箇所の背景色] [-cc マッチ箇所(キャプチャグループ)の文字色]
rem                 [-fc マッチ箇所の文字色] [-Q/-Interactive]
rem
rem
rem     正規表現                  .NET準拠の正規表現を指定します。
rem                               指定がない場合は入力プロンプトが表示されます。
rem     検索対象フォルダー        指定がない場合は選択ダイアログボックスが表示されます。
rem     対象ファイル名            対象ファイル名をカンマ区切りで指定します。ワイルドカードの
rem                               使用が可能です。既定値は"*"です。(例: "*.c, *.h")
rem     -e 文字コード種別         BOM(Byte Order Mark)のないファイルの文字コード。(例: "UTF8")
rem     -g キャプチャグループ     キャプチャグループの名前または番号を指定します。既定値は"0"です。
rem     -h                        HTMLファイルを出力します。
rem     -i                        検索時に大文字小文字を区別しません。
rem     -n                        全角文字を半角文字に変換してから検索します。
rem                               カナ・数字の全角/半角を区別したくない場合に使用します。
rem     -r                        サブフォルダーに対する再帰的検索のスイッチです。
rem     -s                        単純文字列検索のスイッチです。
rem     -x 除外フィルター         除外ファイル名をカンマ区切りで指定します。ワイルドカードの
rem                               使用が可能です。(例: "*.img, *.dat")
rem                               なお、以下のバイナリ形式ファイルは既定で除外されます。
rem                               "*.exe, *.dll, *.lnk, *.zip, *.bmp, *.gif, *.jpg, *.png"
rem     -bc ConsoleColor          マッチ箇所の背景色
rem     -cc ConsoleColor          マッチ箇所(キャプチャグループ)の文字色
rem     -fc ConsoleColor          マッチ箇所の文字色
rem     -Q                        対話モードを強制します。
rem
rem     Created by earthdiver1
rem     Version 2.00
rem     クリエイティブ・コモンズ 表示 - 継承 4.0 国際 ライセンスの下に提供されています。
rem
rem ----------------------------------------------------------------------------
echo %CMDCMDLINE% | findstr /i /c:"%~nx0" >NUL && set DC=1
rem 以下はPowerShellスクリプトをバッチファイルの中に埋め込むためのプリアンブルです。
rem デバッグ時は拡張子を.ps1に変更してPowerShellコンソール上から実行してください。
set BATCH_ARGS=%*
if defined BATCH_ARGS set BATCH_ARGS=%BATCH_ARGS:"=\"%
if defined BATCH_ARGS set BATCH_ARGS=%BATCH_ARGS:^^=^% 
set P_CMD=$DoubleClicked=0%DC%;$PSScriptRoot='%~dp0'.TrimEnd('\');$input^|^
&([ScriptBlock]::Create((${%~f0}^|Out-String)))
endlocal & PowerShell -NoProfile -Command "%P_CMD%" %BATCH_ARGS%
exit/b
rem ----------------------------------------------------------------------------
: バッチコマンド(PowerShellコメント)終了 #>
#Requires -Version 3
param (
    [String]$Pattern,
    [String]$Dir,
    [String]$Include                              = "*",
    [Alias("e")][String]$Encoding                 = "Default",
    [Alias("x")][String]$Exclude                  = "",
    [Alias("g")][String]$Group                    = "0",
    [Alias("h")][Switch]$HtmlOutput               = $False,
    [Alias("i")][Switch]$IgnoreCase               = $False,
    [Alias("n")][Switch]$Narrow                   = $False,
    [Alias("r")][Switch]$Recurse                  = $False,
    [Alias("s")][Switch]$SimpleMatch              = $False,
    [Alias("bc")][ConsoleColor]$BackgroundColor   = "Blue",
    [Alias("cc")][ConsoleColor]$CapturegroupColor = "Red",
    [Alias("fc")][ConsoleColor]$ForegroundColor   = "White",

    [Alias("Q")][Switch]$Interactive = $False
)

#$DebugPreference = "Continue"

Function RegExS {
<#
	.SYNOPSIS
		正規表現を用いたテキスト検索をおこないます。
	
	.DESCRIPTION
		フォルダーツリーの中の複数のテキストファイルに対して正規表現による一括検索を
		おこなうことができます。
	
	.PARAMETER Pattern
		正規表現の文字列です。

	.PARAMETER Dir
		検索対象のフォルダーのパスを指定します。
	
	.PARAMETER Include
		対象ファイル名をカンマ区切りで指定します。ワイルドカードの使用が可能で、
		既定値は"*"です。(例:"*.cpp, *.h")
	
	.PARAMETER Encoding
		BOM(Byte Order Mark)の無いテキストファイルの文字コードを指定します。
		規定値は"Default"です。(別名: -e) 

	.PARAMETER BackgroundColor
		マッチ箇所の背景色を指定します。(別名: -bc)
		規定値は "Blue" です。

	.PARAMETER CapturegroupColor
		マッチ箇所(キャプチャグループ)の文字色を指定します。(別名: -cc)
		規定値は "Red" です。

	.PARAMETER ForegroundColor
		マッチ箇所の文字色を指定します。(別名: -fc)
		規定値は "White" です。

	.PARAMETER Group
		キャプチャグループの名前または番号を指定します。(別名: -g)
		規定値は "0" です。

	.PARAMETER HtmlOutput
		本スイッチの指定時にはHTMLファイルを出力します。(別名: -h)

	.PARAMETER IgnoreCase
		本スイッチの指定時には大文字、小文字を区別しません。(別名: -i)

	.PARAMETER Narrow
		本スイッチの指定時には検索前に全角文字を半角文字に変換します。(別名: -n)
		カナ・数字の全角/半角を区別したくない場合に使用します。

	.PARAMETER Recurse
		本スイッチの指定時にはサブフォルダー内を再帰的に検索します。(別名: -r)
	
	.PARAMETER SimpleMatch
		本スイッチの指定時には単純な文字列検索をおこないます。(別名: -s)

	.PARAMETER Exclude
		除外ファイル名をカンマ区切りで指定します。(別名: -x)
		ワイルドカードの使用が可能です。(例: "*.img, *.dat")
		なお、以下のバイナリ形式ファイルは既定で除外されます。
		*.exe, *.dll, *.lnk, *.zip, *.bmp, *.gif, *.jpg, *.png
	
	.NOTES
		Author:   earthdiver1
		Version:  V2.00
		クリエイティブ・コモンズ 表示 - 継承 4.0 国際 ライセンスの下に提供されています。

#>
    param (
        [String]$Pattern,
        [String]$Dir,
        [String]$Include = "*",
        [ValidateSet("", "Unknown", "String", "Unicode", "Byte", "BigEndianUnicode", `
                     "UTF8", "UTF7", "UTF32", "Ascii", "Default", "Oem", "BigEndianUTF32")]
        [Alias("e")][String]$Encoding                 = "Default",
        [Alias("x")][String]$Exclude                  = "",
        [Alias("g")][String]$Group                    = "0",
        [Alias("h")][Switch]$HtmlOutput,
        [Alias("i")][Switch]$IgnoreCase,
        [Alias("n")][Switch]$Narrow,
        [Alias("r")][Switch]$Recurse,
        [Alias("s")][Switch]$SimpleMatch,
        [Alias("bc")][ConsoleColor]$BackgroundColor   = "Blue",
        [Alias("cc")][ConsoleColor]$CapturegroupColor = "Red",
        [Alias("fc")][ConsoleColor]$ForegroundColor   = "White"
    )
############ Edit Here ############
    $BinaryFiles = "*.exe, *.dll, *.lnk, *.zip, *.bmp, *.gif, *.jpg, *.png"
    $HtmlFile = "$($script:PSScriptRoot)\RegExS_Output.htm"
#   $HtmlFile = "$($script:PSScriptRoot)\RegExS_Output_$((Get-Date).ToString('yyyyMMddHHmm')).htm"
###################################
    if (-not $Pattern) { Write-Host "Pattern の指定がありません。" -Fore Red; Get-Help RegExS; return }
    if (-not $Dir)     { Write-Host "Dir の指定がありません。"     -Fore Red; Get-Help RegExS; return }
    $Dir = Convert-Path -LiteralPath $Dir
    if (-not $Dir)     { Write-Host "Dir は存在しません。"         -Fore Red; Get-Help RegExS; return }
    [Array]$IsContainer = Get-Item $Dir | %{ $_.PSIsContainer }
    if ((-not $Recurse) -and $IsContainer.Length -eq 1 -and $IsContainer[0]) { $Dir += "\*" }
    if ($SimpleMatch)  { $Pattern = [regex]::Escape($Pattern) }
    if ($IgnoreCase)   { $Pattern = "(?i)" + $Pattern }
    if ($HtmlOutput) { HtmlHeader }
    [String[]]$IncludeList = $Include -Split "," | %{ $_.Trim() }
    [String[]]$ExcludeList = ($Exclude + "," + $BinaryFiles) -Split "," | %{ $_.Trim() } | ?{ $_ }
    $global:ErrorView = "CategoryView"
    if ($IncludeList.Length -eq 1) { # "-Filter" の方が "-Include" よりも速い
        $files = Get-ChildItem $Dir -Filter $Include      -Exclude $ExcludeList -Recurse:$Recurse -File
    } else {
        $files = Get-ChildItem $Dir -Include $IncludeList -Exclude $ExcludeList -Recurse:$Recurse -File
    }
    $global:ErrorView = "NormalView"
    $ErrorActionPreference = "Stop"
    trap [System.Exception] {
        Write-Host "システム例外が発生しました。" -Fore Red
        Write-Host $Error[0].ToString() $Error[0].InvocationInfo.PositionMessage
        if ($HtmlOutput) {
            HtmlFooter
            try { 
                [Text.Encoding]::UTF8.GetBytes($script:Html.ToString()) | Set-Content -Path $HtmlFile -Encoding Byte # UTF-8N
                [void]$script:Html.Clear()
            } catch [System.Exception] {}
        }
        return
    }
    [Int]$Nmfile = 0
    [Int]$Nmatch = 0
    [Int]$Nmline = 0
    [Int]$Nmchar = 0
    if ($files) {
        foreach ($file in $files) {
            Write-Debug "RegExS: $($file.FullName)"
            try {
                $enc = GetEncodingFromBOM $file
                if (-not $enc) { 
                    if (IsBinary $file) {
                        Write-Host "バイナリ形式ファイル $($file.FullName) をスキップします。" -Fore Green
                        continue
                    }
                    $enc = $Encoding 
                }
                $io = Get-Content $file.FullName -Encoding $enc -Raw
            } catch [System.UnauthorizedAccessException], `
                    [System.Management.Automation.ItemNotFoundException], `
                    [System.IO.IOException] {
                Write-Host "$($Error[0].Exception.Message) 処理を継続します。" -Fore Red
                if ($HtmlOutput) {
                    [void]$script:Html.Append("<span class=`"y`">$(Htmlify $Error[0].Exception.Message) 処理を継続します。</span>`n")
                }
                continue
            }
            if ($Narrow) {
                Add-Type -AssemblyName "Microsoft.VisualBasic"
                $tmpfile = [System.IO.Path]::GetTempFileName()
                [Microsoft.VisualBasic.Strings]::StrConv($io,[Microsoft.VisualBasic.VbStrConv]::Narrow) >> $tmpfile
                $Pattern = [Microsoft.VisualBasic.Strings]::StrConv($Pattern,[Microsoft.VisualBasic.VbStrConv]::Narrow)
                [Array]$Matches = Select-String -Pattern $Pattern -CaseSensitive -LiteralPath $tmpfile -Encoding $enc `
                                | ?{ $_.Matches.Groups.Name -eq $Group -and $_.Matches.Groups.Success }
                Remove-Item $tmpfile -Force
            } else {
                [Array]$Matches = Select-String -Pattern $Pattern -CaseSensitive -LiteralPath $file.FullName -Encoding $enc `
                                | ?{ $_.Matches.Groups.Name -eq $Group -and $_.Matches.Groups.Success }
            }
            if ($Matches) {
                $Nmfile++
                Write-Host $file.FullName -Fore Yellow
                $Regex = New-Object System.Text.RegularExpressions.Regex $Pattern
                if (-not $HtmlOutput) {
                    if ($Group -eq "0") {
                        foreach ($mm in $Matches) {                        
                            $Nmline++
                            Write-Host $("{0,5}:" -F $mm.LineNumber) -NoNewline
                            $index = 0
                            $m = $Regex.Match($mm.Line, $index).Groups[0]
                            while ($m.Success) {
                                $Nmatch++
                                if ($m.Index -ge $mm.Line.Length) { break }
                                if ($m.Length -gt 0) {
                                    $Nmchar += $m.Length
                                    Write-Host $mm.Line.SubString($index, $m.Index - $index) -NoNewline
                                    Write-Host $m.Value -Back $BackgroundColor -Fore $ForegroundColor -NoNewline
                                    $index = $m.Index + $m.Length
                                } else {
                                    Write-Host $mm.Line.SubString($index, $m.Index - $index + 1) -NoNewline
                                    $index = $m.Index + 1
                                }
                                $m = $Regex.Match($mm.Line, $index).Groups[0]
                            }
                            Write-Host $mm.Line.SubString($index)
                        }
                    } else {
                        foreach ($mm in $Matches) {                        
                            $Nmline++
                            Write-Host $("{0,5}:" -F $mm.LineNumber) -NoNewline
                            $index = 0
                            $match = $Regex.Match($mm.Line, $index)
                            $m = $match.Groups[$Group]
                            while ($m.Success) {
                                $Nmatch++
                                if ($m.Index -ge $mm.Line.Length) { break }
                                $m0 = $match.Groups[0]
                                if ($m0.Length -gt 0) {
                                    $Nmchar += $m.Length
                                    Write-Host $mm.Line.SubString($index, $m0.Index - $index) -NoNewline
                                    Write-Host $mm.Line.SubString($m0.Index, $m.Index - $m0.Index) `
                                               -Back $BackgroundColor -Fore $ForegroundColor -NoNewline
                                    Write-Host $m.Value -Back $BackgroundColor -Fore $CapturegroupColor -NoNewline 
                                    $index = $m0.Index + $m0.Length
                                    $i = $m.Index  + $m.Length
                                    Write-Host $mm.Line.SubString($i, $index - $i) -Back $BackgroundColor -Fore $ForegroundColor -NoNewline 
                                } else {
                                    Write-Host $mm.Line.SubString($index, $m0.Index - $index + 1) -NoNewline
                                    $index = $m0.Index + 1
                                }
                                $match = $Regex.Match($mm.Line, $index)
                                $m = $match.Groups[$Group]
                            }
                            Write-Host $mm.Line.SubString($index)
                        }
                    }
                } else {
                    [void]$script:Html.Append("<a href=`"file:///$($file.FullName)`" type=`"text`" class=`"y`">$($file.FullName)</a>`n")
                    if ($Group -eq "0") {
                        foreach ($mm in $Matches) {
                            $Nmline++
                            [void]$script:Html.Append(("{0,5}:" -F $mm.LineNumber))
                            $index = 0
                            $m = $Regex.Match($mm.Line, $index).Groups[0]
                            while ($m.Success) {
                                $Nmatch++
                                if ($m.Index -ge $mm.Line.Length) { break }
                                if ($m.Length -gt 0) {
                                    $Nmchar += $m.Length
                                    [void]$script:Html.Append((Htmlify $mm.Line.SubString($index, $m.Index - $index)))
                                    [void]$script:Html.Append("<span class=`"fc`">$(Htmlify $m.Value)</span>")
                                    $index = $m.Index + $m.Length
                                } else {
                                    [void]$script:Html.Append($(Htmlify $mm.Line.SubString($index, $m.Index - $index + 1)))
                                    $index = $m.Index + 1
                                }
                                $m = $Regex.Match($mm.Line, $index).Groups[0]
                            }
                            [void]$script:Html.Append("$(Htmlify $mm.Line.SubString($index))`n")
                        }
                    } else {
                        foreach ($mm in $Matches) {
                            $Nmline++
                            [void]$script:Html.Append(("{0,5}:" -F $mm.LineNumber))
                            $index = 0
                            $match = $Regex.Match($mm.Line, $index)
                            $m = $match.Groups[$Group]
                            while ($m.Success) {
                                $Nmatch++
                                if ($m.Index -ge $mm.Line.Length) { break }
                                $m0 = $match.Groups[0]
                                if ($m0.Length -gt 0) {
                                    $Nmchar += $m.Length
                                    [void]$script:Html.Append((Htmlify $mm.Line.SubString($index, $m0.Index - $index)))
                                    [void]$script:Html.Append("<span class=`"fc`">$(Htmlify $mm.Line.SubString($m0.Index, $m.Index - $m0.Index))</span>")
                                    [void]$script:Html.Append("<span class=`"cc`">$(Htmlify $m.Value)</span>")
                                    $index = $m0.Index + $m0.Length
                                    $i = $m.Index  + $m.Length
                                    [void]$script:Html.Append("<span class=`"fc`">$(Htmlify $mm.Line.SubString($i, $index - $i))</span>")
                                } else {
                                    [void]$script:Html.Append($(Htmlify $mm.Line.SubString($index, $m0.Index - $index + 1)))
                                    $index = $m0.Index + 1
                                }
                                $match = $Regex.Match($mm.Line, $index)
                                $m = $match.Groups[$Group]
                            }
                            [void]$script:Html.Append("$(Htmlify $mm.Line.SubString($index))`n")
                        }
                    }
                }
            }
        }
    }
    Write-Host "$Nmfile ファイル、$Nmline 行、$Nmatch 件、$Nmchar 文字の一致がありました。" -Fore Green
    if ($HtmlOutput) {
        [void]$script:Html.Append("<span class=`"g`">$Nmfile ファイル、$Nmline 行、$Nmatch 件、$Nmchar 文字の一致がありました。</span>`n")
        HtmlFooter
        try {
            [Text.Encoding]::UTF8.GetBytes($script:Html.ToString()) | Set-Content -Path $HtmlFile -Encoding Byte # UTF-8N
            [void]$script:Html.Clear()
            Write-Host "$HtmlFile に結果を出力しました。" -Fore Green
            Start-Process -FilePath "file:///$HtmlFile"
        } catch [System.Exception] {
            Write-Host "Htmlファイルの出力に失敗しました。" -Fore Red
            Write-Host $Error[0].Exception.Message
        }
    }
}

Function IsBinary($File) {
    if ($File.Length -lt 2)        { return $False }
    if ($File.Length -gt 20000000) { return $True  }
    $bytes = Get-Content $File.FullName -ReadCount 4096 -TotalCount 4096 -Encoding Byte
    [Int]$Nbo=0
    [Int]$Nbe=0
    [Int]$Nzo=0
    [Int]$Nze=0
    for ([Int]$i=0; $i -lt $bytes.Length; $i+=2) {
        $Nbo++
        if ($bytes[$i] -eq 0) { $Nzo++ }
    }
    for ([Int]$i=1; $i -lt $bytes.Length; $i+=2) {
        $Nbe++
        if ($bytes[$i] -eq 0) { $Nze++ }
    }
    if (($Nzo+$Nze -gt 0) -and ([System.Math]::Abs($Nzo/$Nbo-$Nze/$Nbe)/($Nbo+$Nbe) -lt 0.1)) { return $True }
    Write-Debug "IsBinary: $($file.Name) $($Nzo+$Nze), $([System.Math]::Abs($Nzo/$Nbo-$Nze/$Nbe)/($Nbo+$Nbe))"
    return $False
}

Function GetEncodingFromBOM($File) {
    $bytes = Get-Content $File.FullName -ReadCount 4 -TotalCount 4 -Encoding Byte
    $string = ($bytes | %{ "{0:X2}" -F $_ }) -Join ""
    switch -Regex ($string) {
       "^EFBBBF"              { $enc="UTF8"             ; break }
       "^FFFE0000"            { $enc="UTF32"            ; break }
       "^FFFE"                { $enc="Unicode"          ; break }
       "^0000FEFF"            { $enc="BigEndianUTF32"   ; break }
       "^FEFF"                { $enc="BigEndianUnicode" ; break }
       "^2B2F76(38|39|2B|2F)" { $enc="UTF7"             ; break }
       Default                { $enc="" }
    }
    Write-Debug "GetEncodingFromBOM: $($File.Name) $($string) $($enc)"
    return $enc
}

Function RGBColor([ConsoleColor]$Color) {
    switch -Exact ($Color) {
        "Black"       { return "#000000" }
        "DarkBlue"    { return "#000080" }
        "DarkGreen"   { return "#008000" }
        "DarkCyan"    { return "#008080" }
        "DarkRed"     { return "#800000" }
        "DarkMagenta" { return "#012456" }
        "DarkYellow"  { return "#EEEDF0" }
        "Gray"        { return "#C0C0C0" }
        "DarkGray"    { return "#808080" }
        "Blue"        { return "#0000FF" }
        "Green"       { return "#008000" }
        "Cyan"        { return "#00FFFF" }
        "Red"         { return "#FF0000" }
        "Magenta"     { return "#FF00FF" }
        "Yellow"      { return "#FFFF00" }
        "White"       { return "#FFFFFF" }
        Default       { return ""        }
    }
}

Function HtmlHeader() {
    $script:Html = New-Object System.Text.StringBuilder
    [void]$script:Html.Append("<!DOCTYPE html>`n")
    [void]$script:Html.Append("<html lang=`"ja`">`n")        # <- You may want to change this
    [void]$script:Html.Append("<meta charset=`"UTF-8`">`n")
    [void]$script:Html.Append("<head>`n")
    [void]$script:Html.Append("<title>RegExS Output</title>`n")
    [void]$script:Html.Append("<style type=`"text/css`">`n")
    [void]$script:Html.Append("body {color:#ffffff; background-color:$(RGBColor("DarkMagenta"))}`n")
    [void]$script:Html.Append("pre{white-space:pre-wrap}`n")
    [void]$script:Html.Append(".fc {color:$(RGBColor($ForegroundColor)); background-color:$(RGBColor($BackgroundColor))}`n")
    [void]$script:Html.Append(".cc {color:$(RGBColor($CapturegroupColor)); background-color:$(RGBColor($BackgroundColor))}`n")
    [void]$script:Html.Append(".g {color:lime}`n")
    [void]$script:Html.Append(".y {color:yellow}`n")
    [void]$script:Html.Append("</style>`n")
    [void]$script:Html.Append("</head>`n<body>`n<pre>`n")
}

Function HtmlFooter() {
    [void]$script:Html.Append("</pre>`n</body>`n</html>")
}

Function Htmlify($t) {
    $t = $t -Replace "&", "&amp;"
    $t = $t -Replace ">", "&gt;"
    $t = $t -Replace "<", "&lt;"
    $t = $t -Replace """", "&quot;"
    return $t
}

Function Pause_and_Exit() {
    Write-Host "終了するには何かキーを押してください . . ." -Fore Green
    $Host.UI.RawUI.FlushInputBuffer()
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") | Out-Null
    exit
}

Function Main() {
    if ($DoubleClicked) { $Interactive = $True  }
    if ($Interactive) {
        if ($Pattern) {
            Write-Host "検索対象の正規表現を入力してください。[$Pattern]:" -NoNewline -Fore Green
            $Answer = ""
            try { $Answer = Read-Host } catch [System.Exception] {}
            if ($Answer) { $Pattern = $Answer }
        } else {
            Write-Host "検索対象の正規表現を入力してください。:" -NoNewline -Fore Green
            try { $Pattern = Read-Host } catch [System.Exception] {}
            if (-not $Pattern) { Pause_and_Exit }
        }

        Write-Host "キャプチャグループ(名前/番号)を指定してください。[$Group]:" -NoNewline -Fore Green
        $Answer = ""
        try { $Answer = (Read-Host).Trim() } catch [System.Exception] {}
        if ($Answer) { $Group = $Answer }

        Write-Host "検索対象のフォルダーを指定してください。" -Fore Green
        Add-Type -AssemblyName System.Windows.Forms
        $fbd = New-Object System.Windows.Forms.FolderBrowserDialog
        $fbd.ShowNewFolderButton = $false
        $fbd.Description = "検索対象のフォルダーを指定してください。"
        if ($Dir -and (Test-Path -LiteralPath $Dir)) {
            $fbd.SelectedPath = Convert-Path -LiteralPath $Dir
        } else {
            $fbd.SelectedPath = [string]$PWD
        }
        $Result = $fbd.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true}))
        if ($Result -eq [System.Windows.Forms.DialogResult]::OK) { 
            $Dir = $fbd.SelectedPath 
        } else {
            Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit
        }
        $fbd.Dispose()
        #Begin Get-WindowFocus
        Add-Type @"
            using System;
            using System.Runtime.InteropServices;
            public class SFW {
                [DllImport("user32.dll")]
                [return: MarshalAs(UnmanagedType.Bool)]
                public static extern bool SetForegroundWindow(IntPtr hWnd);
            }
"@
        $PPID=$PID
        For ([Int]$i=0; $i -lt 2; $i++) {
            $PPID=(Get-WmiObject Win32_Process -Filter "ProcessID=$PPID").ParentProcessID
            try {
                $WindowTitle  = (Get-Process -ID $PPID -ErrorAction SilentlyContinue).MainWindowTitle
                $WindowHandle = (Get-Process -ID $PPID -ErrorAction SilentlyContinue).MainWindowHandle
                if ($WindowTitle) { 
                    [void][SFW]::SetForegroundWindow($WindowHandle)
                    break
                }
            } catch [System.Exception] { break }
        }
        #End Get-WindowFocus

        Write-Host "サブフォルダーを検索に含めますか。Y/N [$(if($Recurse){"Y"}else{"N"})]:" -NoNewline -Fore Green
        try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
        switch ($Answer) {
               "Y" { $Recurse = $True  }
               "N" { $Recurse = $False }
               ""  { }
          default  { Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit }
        }

        Write-Host "対象ファイル名を入力してください(ワイルドカード使用可)。[$Include]:" -NoNewline -Fore Green
        $Answer = ""
        try { $Answer = (Read-Host).Trim() } catch [System.Exception] {}
        if ($Answer) { $Include = $Answer }

        Write-Host "その他のオプションを指定しますか。Y/N [N]:" -NoNewline -Fore Green
        $Answer = ""
        try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
        if ($Answer -eq "Y") {
            Write-Host "Htmlファイルを出力しまますか。Y/N [$(if($HtmlOutput){"Y"}else{"N"})]:" -NoNewline -Fore Green
            try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
            switch ($Answer) {
                   "Y" { $HtmlOutput = $True  }
                   "N" { $HtmlOutput = $False }
                   ""  { }
              default  { Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit }
            }

            Write-Host "単純文字列検索を有効にしますか。Y/N [$(if($SimpleMatch){"Y"}else{"N"})]:" -NoNewline -Fore Green
            try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
            switch ($Answer) {
                   "Y" { $SimpleMatch = $True  }
                   "N" { $SimpleMatch = $False }
                   ""  { }
              default  { Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit }
            }

            Write-Host "大小文字を区別しないようにしますか。Y/N [$(if($IgnoreCase){"Y"}else{"N"})]:" -NoNewline -Fore Green
            try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
            switch ($Answer) {
                   "Y" { $IgnoreCase = $True  }
                   "N" { $IgnoreCase = $False }
                   ""  { }
              default  { Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit }
            }

            Write-Host "検索前に全角文字を半角文字に変換しますか。Y/N [$(if($Narrow){"Y"}else{"N"})]:" -NoNewline -Fore Green
            try { $Answer = (Read-Host).Trim().ToUpper() } catch [System.Exception] {}
            switch ($Answer) {
                   "Y" { $Narrow = $True  }
                   "N" { $Narrow = $False }
                   ""  { }
              default  { Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit }
            }

            Write-Host "除外ファイル名を入力してください(ワイルドカード使用可)。[$Exclude]:" -NoNewline -Fore Green
            $Answer = ""
            try { $Answer = (Read-Host).Trim() } catch [System.Exception] {}
            if ($Answer) { $Exclude = $Answer }

            Write-Host "Byte Order Markの無いファイルの文字コード種別を入力してください。[$Encoding]:" -NoNewline -Fore Green
            $Answer = ""
            try { $Answer = (Read-Host).Trim() } catch [System.Exception] {}
            if ($Answer) { 
                $Encoding = $Answer 
                $EncodingList = @("unkown", "string", "unicode", "byte", "bigendianunicode", `
                                  "utf8", "utf7", "utf32", "ascii", "default", "oem", "bigendianutf32")
                if (-not ($EncodingList -Contains $Encoding.ToLower())) {
                    Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit
                }
            }
        } elseif ($Answer -ne "N" -and $Answer -ne "") {
            Write-Host "入力値が不正です" -Fore Red; Pause_and_Exit
        }
    }

    RegExS $Pattern $Dir $Include -e $Encoding -g $Group -h:$HtmlOutput -i:$IgnoreCase -n:$Narrow -r:$Recurse `
                                  -s:$SimpleMatch -x $Exclude `
                                  -bc $BackgroundColor -cc $CapturegroupColor -fc $ForegroundColor 

    if ($Interactive) { Pause_and_Exit }
}

Main