|
1 | | -<# |
| 1 | +<# |
2 | 2 | .SYNOPSIS |
3 | 3 | Search and replace a pattern in the given files by the replacement |
4 | 4 | .DESCRIPTION |
5 | 5 | This PowerShell script searches and replaces a pattern in the given files by the replacement. |
6 | 6 | .PARAMETER pattern |
7 | | - Specifies the pattern to look for |
| 7 | + Specifies the text pattern to look for |
8 | 8 | .PARAMETER replacement |
9 | | - Specifies the replacement |
10 | | -.PARAMETER files |
| 9 | + Specifies the text replacement |
| 10 | +.PARAMETER filePattern |
11 | 11 | Specifies the file to scan |
12 | 12 | .EXAMPLE |
13 | 13 | PS> ./replace-in-files NSA "No Such Agency" C:\Temp\*.txt |
|
17 | 17 | Author: Markus Fleschutz | License: CC0 |
18 | 18 | #> |
19 | 19 |
|
20 | | -param([string]$pattern = "", [string]$replacement = "", [string]$files = "") |
| 20 | +param([string]$pattern = "", [string]$replacement = "", [string]$filePattern = "") |
21 | 21 |
|
22 | | -function ReplaceInFile { param([string]$FilePath, [string]$Pattern, [string]$Replacement) |
| 22 | +function ReplaceInFile { param([string]$path, [string]$pattern, [string]$replacement) |
23 | 23 |
|
24 | | - [System.IO.File]::WriteAllText($FilePath, |
25 | | - ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement) |
| 24 | + [System.IO.File]::WriteAllText($path, |
| 25 | + ([System.IO.File]::ReadAllText($path) -replace $pattern, $replacement) |
26 | 26 | ) |
27 | 27 | } |
28 | 28 |
|
29 | 29 | try { |
30 | | - if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" } |
31 | | - if ($replacement -eq "" ) { $replacement = read-host "Enter replacement" } |
32 | | - if ($files -eq "" ) { $files = read-host "Enter files" } |
| 30 | + if ($pattern -eq "" ) { $pattern = Read-Host "Enter the text pattern to look for" } |
| 31 | + if ($replacement -eq "" ) { $replacement = Read-Host "Enter the text replacement" } |
| 32 | + if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file pattern" } |
33 | 33 |
|
34 | | - $StopWatch = [system.diagnostics.stopwatch]::startNew() |
35 | | - |
36 | | - $fileList = (get-childItem -path "$files" -attributes !Directory) |
37 | | - foreach($file in $fileList) { |
| 34 | + $stopWatch = [system.diagnostics.stopwatch]::startNew() |
| 35 | + $files = (Get-ChildItem -path "$filePattern" -attributes !Directory) |
| 36 | + foreach($file in $files) { |
38 | 37 | ReplaceInFile $file $pattern $replacement |
39 | 38 | } |
40 | | - [int]$Elapsed = $StopWatch.Elapsed.TotalSeconds |
41 | | - "OK, replaced '$pattern' by '$replacement' in $($fileList.Count) files in $Elapsed sec." |
| 39 | + [int]$elapsed = $stopWatch.Elapsed.TotalSeconds |
| 40 | + "✔️ Replaced '$pattern' by '$replacement' in $($files.Count) files in $elapsed sec" |
42 | 41 | exit 0 # success |
43 | 42 | } catch { |
44 | 43 | "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])" |
|
0 commit comments