forked from fleschutz/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplace-in-files.ps1
More file actions
executable file
·63 lines (57 loc) · 1.69 KB
/
replace-in-files.ps1
File metadata and controls
executable file
·63 lines (57 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<#
.SYNOPSIS
Search and replace a pattern in the given files by the replacement
.DESCRIPTION
This PowerShell script searches and replaces a pattern in the given files by the replacement.
.PARAMETER pattern
Specifies the pattern to look for
.PARAMETER replacement
Specifies the replacement
.PARAMETER files
Specifies the file to scan
.PARAMETER recursive
flag to search recursively
.EXAMPLE
PS> ./replace-in-files NSA "No Such Agency" C:\Temp\*.txt -recursive
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param(
[string]$pattern = "",
[string]$replacement = "",
[string]$files = "",
[switch]$recursive = $false
)
function ReplaceInFile {
param(
[string]$FilePath,
[string]$Pattern,
[string]$Replacement
)
[System.IO.File]::WriteAllText($FilePath,
([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
)
}
try {
if ($pattern -eq "" ) { $pattern = read-host "Enter search pattern" }
if ($replacement -eq "" ) { $replacement = read-host "Enter replacement" }
if ($files -eq "" ) { $files = read-host "Enter files" }
$StopWatch = [system.diagnostics.stopwatch]::startNew()
if ($recursive) {
$fileList = (get-childItem -path "$files" -file -recurse)
}
else {
$fileList = (get-childItem -path "$files" -file)
}
foreach($file in $fileList) {
ReplaceInFile $file $pattern $replacement
}
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
"OK, replaced '$pattern' by '$replacement' in $($fileList.Count) files in $Elapsed sec."
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}