Update search-files.ps1

This commit is contained in:
Markus Fleschutz 2024-05-08 12:58:57 +02:00
parent 60c1004a40
commit 9a9d83dfc8

View File

@ -1,39 +1,37 @@
<# <#
.SYNOPSIS .SYNOPSIS
Searches for a pattern in files Searches for a text pattern in files
.DESCRIPTION .DESCRIPTION
This PowerShell script searches for a pattern in the given files. This PowerShell script searches for the given pattern in the given files.
.PARAMETER pattern .PARAMETER textPattern
Specifies the search pattern Specifies the text pattern to search for
.PARAMETER files .PARAMETER filePattern
Specifies the files Specifies the files to search
.EXAMPLE .EXAMPLE
PS> ./search-files UFO C:\Temp\*.txt PS> ./search-files UFO C:\Temp\*.txt
...
Found 'UFO' at 9 locations.
.LINK .LINK
https://github.com/fleschutz/PowerShell https://github.com/fleschutz/PowerShell
.NOTES .NOTES
Author: Markus Fleschutz | License: CC0 Author: Markus Fleschutz | License: CC0
#> #>
param([string]$pattern = "", [string]$files = "") param([string]$textPattern = "", [string]$filePattern = "")
function ListLocations { param([string]$Pattern, [string]$Path) function ListLocations { param([string]$Pattern, [string]$Path)
$List = Select-String -Path $Path -Pattern "$Pattern" $list = Select-String -path $Path -pattern "$Pattern"
foreach ($Item in $List) { foreach ($item in $list) {
New-Object PSObject -Property @{ New-Object PSObject -Property @{ 'FILE'="$($item.Path)"; 'LINE'="$($item.LineNumber):$($item.Line)" }
'Path' = "$($Item.Path)"
'Line' = "$($Item.LineNumber)"
'Text' = "$($Item.Line)"
}
} }
write-output "(found $($List.Count) locations with pattern '$pattern')" Write-Output "✔️ Found '$Pattern' at $($list.Count) locations."
} }
try { try {
if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" } if ($textPattern -eq "" ) { $textPattern = Read-Host "Enter the text pattern (e.g. 'UFO')" }
if ($files -eq "" ) { $files = read-host "Enter path to files" } if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file pattern (e.g. '*.txt')" }
ListLocations $pattern $files | format-table -property Path,Line,Text ListLocations $textPattern $filePattern | Format-Table -property FILE,LINE -autoSize
exit 0 # success exit 0 # success
} catch { } catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])" "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"