2023-10-31 13:03:45 +01:00
|
|
|
|
<#
|
2021-09-27 08:58:31 +02:00
|
|
|
|
.SYNOPSIS
|
|
|
|
|
Search and replace a pattern in the given files by the replacement
|
2021-10-04 21:29:23 +02:00
|
|
|
|
.DESCRIPTION
|
2022-01-30 10:49:30 +01:00
|
|
|
|
This PowerShell script searches and replaces a pattern in the given files by the replacement.
|
2021-10-16 16:50:10 +02:00
|
|
|
|
.PARAMETER pattern
|
2023-10-31 11:22:55 +01:00
|
|
|
|
Specifies the text pattern to look for
|
2021-10-16 16:50:10 +02:00
|
|
|
|
.PARAMETER replacement
|
2023-10-31 11:22:55 +01:00
|
|
|
|
Specifies the text replacement
|
|
|
|
|
.PARAMETER filePattern
|
2021-10-16 16:50:10 +02:00
|
|
|
|
Specifies the file to scan
|
2021-09-27 08:58:31 +02:00
|
|
|
|
.EXAMPLE
|
2021-10-04 21:29:23 +02:00
|
|
|
|
PS> ./replace-in-files NSA "No Such Agency" C:\Temp\*.txt
|
2021-09-27 08:58:31 +02:00
|
|
|
|
.LINK
|
|
|
|
|
https://github.com/fleschutz/PowerShell
|
2022-01-30 10:49:30 +01:00
|
|
|
|
.NOTES
|
2022-09-06 21:42:04 +02:00
|
|
|
|
Author: Markus Fleschutz | License: CC0
|
2021-09-27 08:58:31 +02:00
|
|
|
|
#>
|
|
|
|
|
|
2023-10-31 11:22:55 +01:00
|
|
|
|
param([string]$pattern = "", [string]$replacement = "", [string]$filePattern = "")
|
2021-09-27 08:58:31 +02:00
|
|
|
|
|
2023-10-31 11:22:55 +01:00
|
|
|
|
function ReplaceInFile { param([string]$path, [string]$pattern, [string]$replacement)
|
2021-09-27 08:58:31 +02:00
|
|
|
|
|
2023-10-31 11:22:55 +01:00
|
|
|
|
[System.IO.File]::WriteAllText($path,
|
|
|
|
|
([System.IO.File]::ReadAllText($path) -replace $pattern, $replacement)
|
2021-09-27 08:58:31 +02:00
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2023-10-31 11:22:55 +01:00
|
|
|
|
if ($pattern -eq "" ) { $pattern = Read-Host "Enter the text pattern to look for" }
|
|
|
|
|
if ($replacement -eq "" ) { $replacement = Read-Host "Enter the text replacement" }
|
|
|
|
|
if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file pattern" }
|
2021-09-27 08:58:31 +02:00
|
|
|
|
|
2023-10-31 11:22:55 +01:00
|
|
|
|
$stopWatch = [system.diagnostics.stopwatch]::startNew()
|
|
|
|
|
$files = (Get-ChildItem -path "$filePattern" -attributes !Directory)
|
|
|
|
|
foreach($file in $files) {
|
2021-09-27 08:58:31 +02:00
|
|
|
|
ReplaceInFile $file $pattern $replacement
|
|
|
|
|
}
|
2023-10-31 11:22:55 +01:00
|
|
|
|
[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
|
|
|
|
|
"✔️ Replaced '$pattern' by '$replacement' in $($files.Count) files in $elapsed sec"
|
2021-09-27 10:09:45 +02:00
|
|
|
|
exit 0 # success
|
2021-09-27 08:58:31 +02:00
|
|
|
|
} catch {
|
2022-04-13 12:06:32 +02:00
|
|
|
|
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
|
2021-09-27 08:58:31 +02:00
|
|
|
|
exit 1
|
|
|
|
|
}
|