
Power Shellで
・Grep検索
できます!
コード
ここでは例として、以下を対象にGrep検索して結果をファイルへ出力します。
対象フォルダ | デスクトップ配下の「sample」フォルダ |
対象ファイル(拡張子等) | *.txt |
対象文字列 | りんご |
出力ファイル | デスクトップ配下の「grep_result.txt」 |
# 対象フォルダ
$targetFolder = "C:\Users\user\Desktop\sample"
# 対象ファイル(拡張子等)
$targetFile = "*.txt"
# 対象文字列
$targetString = "りんご"
# 出力ファイルパス
$outputFile = "C:\Users\user\Desktop\grep_result.txt"
$ws = New-Object -ComObject Wscript.Shell
try
{
Get-ChildItem $targetFolder -Recurse -Filter $targetFile |
Select-String -Pattern $targetString -Encoding default |
Set-Content $outputFile
$ws.popup("Grepに成功しました。")
}
catch [System.IO.IOException]
{
$ws.popup("Grepに失敗しました。`n出力ファイルが開いている可能性があります。")
}
catch
{
$ws.popup("Grepに失敗しました。")
}
実行結果
Grep検索できました。
※文字列「りんご」の記載があるファイルの検索ができました。



参考
上記のコードで使用した以下の詳細は、公式サイトをご確認ください。
●「Get-ChildItem」コマンドレット
●「Select-String」コマンドレット
●「Set-Content」コマンドレット