Skip to content

Instantly share code, notes, and snippets.

@bill-long
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bill-long/10596271 to your computer and use it in GitHub Desktop.
Save bill-long/10596271 to your computer and use it in GitHub Desktop.
Search text files for a given regular expression. This is for when findstr won't cut it due to its limited regexp support.
param(
[Parameter(Position=0, Mandatory=$true)]
[string] $Pattern,
[Parameter(Position=1, Mandatory=$false)]
[string] $File,
[Parameter(Mandatory=$false)]
[string] $Directory,
[Parameter(Mandatory=$false)]
[string] $FileFilter,
[Parameter(Mandatory=$false)]
[switch] $Recurse = $false
)
if ($File.Length -gt 0)
{
# If you specify one file, you can't specify Directory or FileFilter
if ($Directory.Length -gt 0 -or $FileFilter.Length -gt 0 -or $Recurse -eq $true)
{
"Invalid syntax."
return
}
}
else
{
# If you don't specify a file, you MUST specify Directory AND FileFilter
if ($Directory.Length -lt 1 -or $FileFilter.Length -lt 1)
{
"Invalid syntax."
return
}
}
function SearchFile([string] $file, [bool] $displayFileName)
{
$reader = New-Object System.IO.StreamReader($file)
if ($reader -eq $null)
{
return
}
while ($null -ne ($buffer = $reader.ReadLine()))
{
if ($regex.IsMatch($buffer))
{
if ($displayFileName)
{
$file + ": " + $buffer
}
else
{
$buffer
}
}
}
$reader.Close()
}
$regex = New-Object System.Text.RegularExpressions.Regex($Pattern)
if ($File)
{
SearchFile $File $false
}
else
{
if ($Recurse)
{
$files = Get-ChildItem $Directory $FileFilter -Recurse
}
else
{
$files = Get-ChildItem $Directory $FileFilter
}
foreach ($oneFile in $files)
{
if (!($oneFile.PSIsContainer))
{
SearchFile $oneFile.FullName $true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment