PowerShell/Docs/search-files.md

90 lines
2.2 KiB
Markdown
Raw Normal View History

2022-11-17 20:13:00 +01:00
## The PowerShell Script *search-files.ps1*
2021-11-08 21:36:42 +01:00
2022-02-10 09:01:07 +01:00
This PowerShell script searches for a pattern in the given files.
2021-11-08 21:36:42 +01:00
## Parameters
```powershell
2021-12-09 16:19:09 +01:00
search-files.ps1 [[-pattern] <String>] [[-files] <String>] [<CommonParameters>]
2021-11-08 21:36:42 +01:00
-pattern <String>
Specifies the search pattern
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-files <String>
Specifies the files
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
```
## Example
```powershell
PS> ./search-files UFO C:\Temp\*.txt
```
## Notes
2022-11-17 19:46:02 +01:00
Author: Markus Fleschutz | License: CC0
2021-11-08 21:36:42 +01:00
## Related Links
https://github.com/fleschutz/PowerShell
2022-11-17 20:02:26 +01:00
## Source Code
2022-11-17 20:05:34 +01:00
```powershell
2022-11-17 20:02:26 +01:00
<#
.SYNOPSIS
Searches for a pattern in files
.DESCRIPTION
This PowerShell script searches for a pattern in the given files.
.PARAMETER pattern
Specifies the search pattern
.PARAMETER files
Specifies the files
.EXAMPLE
PS> ./search-files UFO C:\Temp\*.txt
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
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 in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
2022-11-17 20:05:34 +01:00
```
2022-11-17 20:02:26 +01:00
2021-11-08 21:36:42 +01:00
*Generated by convert-ps2md.ps1 using the comment-based help of search-files.ps1*