Last active
February 10, 2022 21:01
-
-
Save santisq/dc3c302be515e029cf8c01ca58a60b73 to your computer and use it in GitHub Desktop.
search for a regex pattern in files, alternative to Select-String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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