powershell の勉強として、指定したフォルダ配下の指定した名前のファイル(正規表現)を、指定した文字列で grep するスクリプトを作成した。
grep.ps1
$targetDir = $Args[0] $targetFile = $Args[1] $grepStr = $Args[2] # -Filter はデフォルトで正規表現が有効。 $fullNames = @(Get-ChildItem $targetDir -Recurse -Filter $targetFile | Select-Object FullName) Write-Output "----- Result -----`r`n" | Set-Content result.txt -Encoding Default foreach ($fullName in $fullNames) { # Select-String はデフォルトで正規表現が有効。 # 正規表現を使いたくない場合は「-SimpleMatch」を付ければ良いらしい。 $foundStrings = @(Select-String $grepStr $fullName.fullName) foreach ($foundString in $foundStrings) { Write-Output $foundString | Add-Content result.txt -Encoding Default } }
使い方は、
grep.ps1 "grep対象フォルダ" "grep対象ファイル名(正規表現)" "grep対象文字列"
となる。grep 結果は、カレントディレクトリに result.txt として出力される。
powershell は、こうした処理がコマンドレットで簡単に書けるところが良いと思う。