Skip to content

Instantly share code, notes, and snippets.

@Mehmet-Erkan
Created March 31, 2020 14:41
Show Gist options
  • Save Mehmet-Erkan/c0511d0bbbb3bd5f5ee5e9f83a077dd2 to your computer and use it in GitHub Desktop.
Save Mehmet-Erkan/c0511d0bbbb3bd5f5ee5e9f83a077dd2 to your computer and use it in GitHub Desktop.
PowerShell Cmdlet to search file directory to find patterns with regex
<#
.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