Created
March 31, 2020 14:41
-
-
Save Mehmet-Erkan/c0511d0bbbb3bd5f5ee5e9f83a077dd2 to your computer and use it in GitHub Desktop.
PowerShell Cmdlet to search file directory to find patterns with regex
This file contains 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
<# | |
.Synopsis | |
Find by Regex | |
.DESCRIPTION | |
Find patterns with regex within a file directory | |
.EXAMPLE | |
$pattern = @() | |
$pattern += '<h1>(.*?)</h1>' | |
Get-StringMatch -Path "C:\Temp\myCode\" -Patterns $pattern | |
#> | |
function Get-StringMatch | |
{ | |
[CmdletBinding()] | |
[Alias()] | |
[OutputType()] | |
Param | |
( | |
# Param1 help description | |
[Parameter(Mandatory=$true, | |
ValueFromPipelineByPropertyName=$true, | |
Position=0)] | |
$Path, | |
# regex patterns | |
[Parameter(Mandatory=$true, | |
ValueFromPipelineByPropertyName=$true, | |
Position=0)] | |
[Object[]] | |
$Patterns | |
) | |
Begin | |
{ | |
$files = Get-ChildItem -Path $Path -Recurse -File | |
} | |
Process | |
{ | |
foreach($file in $files) { | |
foreach($pattern in $Patterns) { | |
$match = $file | Select-String -Pattern $pattern | %{ $_.Matches[0].Groups[1].Value } | |
if($match) { | |
$filepath = $file.FullName | |
Write-Host "File: $filepath" -ForegroundColor Magenta | |
Write-Host "=> Pattern found: $pattern" -ForegroundColor green | |
Write-Host "=> Value: $match" -ForegroundColor green | |
} | |
} | |
} | |
} | |
End | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment