PowerShell/Scripts/replace-in-files.ps1

47 lines
1.4 KiB
PowerShell
Raw Normal View History

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
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
Specifies the pattern to look for
.PARAMETER replacement
Specifies the replacement
.PARAMETER files
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
Author: Markus Fleschutz / License: CC0
2021-09-27 08:58:31 +02:00
#>
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-12-18 12:13:29 +01:00
"OK, replaced '$pattern' by '$replacement' in $($fileList.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
}