PowerShell/Scripts/search-files.ps1
Markus Fleschutz b653133853 Add UTF-8 BOM
2021-09-27 10:38:12 +02:00

38 lines
1021 B
PowerShell
Executable File

<#
.SYNOPSIS
search-files.ps1 [<pattern>] [<files>]
.DESCRIPTION
Searches for a pattern in the given files
.EXAMPLE
PS> ./search-files UFO C:\Temp\*.txt
.NOTES
Author: Markus Fleschutz · License: CC0
.LINK
https://github.com/fleschutz/PowerShell
#>
param([string]$pattern = "", [string]$files = "")
function ListLocations { param([string]$Pattern, [string]$Path)
$List = Select-String -Path $Path -Pattern "$Pattern"
foreach ($Item in $List) {
New-Object PSObject -Property @{
'Path' = "$($Item.Path)"
'Line' = "$($Item.LineNumber)"
'Text' = "$($Item.Line)"
}
}
write-output "(found $($List.Count) locations with pattern '$pattern')"
}
try {
if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" }
if ($files -eq "" ) { $files = read-host "Enter path to files" }
ListLocations $pattern $files | format-table -property Path,Line,Text
exit 0 # success
} catch {
"⚠️ Error: $($Error[0]) ($($MyInvocation.MyCommand.Name):$($_.InvocationInfo.ScriptLineNumber))"
exit 1
}