2021-09-27 10:38:12 +02: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
|
|
|
|
|
replace-in-files.ps1 [<pattern>] [<replacement>] [<files>]
|
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
|
|
|
|
.NOTES
|
|
|
|
|
Author: Markus Fleschutz · License: CC0
|
|
|
|
|
.LINK
|
|
|
|
|
https://github.com/fleschutz/PowerShell
|
|
|
|
|
#>
|
|
|
|
|
|
|
|
|
|
param([string]$pattern = "", [string]$replacement = "", [string]$files = "")
|
|
|
|
|
|
|
|
|
|
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" }
|
|
|
|
|
|
2021-09-27 10:04:41 +02:00
|
|
|
|
$StopWatch = [system.diagnostics.stopwatch]::startNew()
|
|
|
|
|
|
|
|
|
|
$fileList = (get-childItem -path "$files" -attributes !Directory)
|
|
|
|
|
foreach($file in $fileList) {
|
2021-09-27 08:58:31 +02:00
|
|
|
|
ReplaceInFile $file $pattern $replacement
|
|
|
|
|
}
|
2021-09-27 10:04:41 +02:00
|
|
|
|
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
|
2021-09-27 10:09:45 +02:00
|
|
|
|
"✔️ replaced '$pattern' by '$replacement' in $($fileList.Count) files in $Elapsed sec"
|
|
|
|
|
exit 0 # success
|
2021-09-27 08:58:31 +02:00
|
|
|
|
} catch {
|
|
|
|
|
"⚠️ Error: $($Error[0]) ($($MyInvocation.MyCommand.Name):$($_.InvocationInfo.ScriptLineNumber))"
|
|
|
|
|
exit 1
|
|
|
|
|
}
|