Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active February 10, 2022 21:01
Show Gist options
  • Save santisq/dc3c302be515e029cf8c01ca58a60b73 to your computer and use it in GitHub Desktop.
Save santisq/dc3c302be515e029cf8c01ca58a60b73 to your computer and use it in GitHub Desktop.
search for a regex pattern in files, alternative to Select-String
using namespace System.IO
function Find-String {
param(
[parameter(ValueFromPipeline, Mandatory)]
[Alias('PSPath')]
[FileInfo]$Path,
[parameter(Mandatory, Position = 0)]
[regex]$Pattern,
[switch]$AllMatches,
[int[]]$Context
)
process {
$content = [File]::ReadAllText($Path)
$match = if($AllMatches.IsPresent) {
$Pattern.Matches($content)
}
else {
$Pattern.Match($content)
}
if($match.Success -notcontains $true) {
return
}
foreach($m in $match) {
$out = [ordered]@{
Path = $path.FullName
Value = $m.Value
Index = $m.Index
Length = $m.Length
}
if($PSBoundParameters.ContainsKey('Context')) {
$before = $m.Index
$after = $m.Index + $m.Length
$contextBefore = $Context[0]
$contextAfter = $Context[1]
while($contextBefore-- -and $before) {
$before--
}
while($contextAfter-- -and $after -lt $content.Length) {
$after++
}
$out.Context = (-join $content[$before..$after]).Trim()
}
[pscustomobject]$out
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment