PowerShell/scripts/replace-in-files.ps1

45 lines
1.6 KiB
PowerShell
Raw Normal View History

2024-10-01 15:24:16 +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
2024-10-01 13:37:53 +02:00
Specifies the text pattern to search for (ask user by default)
2021-10-16 16:50:10 +02:00
.PARAMETER replacement
2024-10-01 13:37:53 +02:00
Specifies the text replacement (ask user by default)
2023-10-31 11:22:55 +01:00
.PARAMETER filePattern
2024-10-01 13:37:53 +02:00
Specifies the file search pattern (ask user by default)
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
2024-10-01 13:37:53 +02:00
function ReplaceInFile([string]$path, [string]$pattern, [string]$replacement) {
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 {
2024-10-01 13:37:53 +02:00
if ($pattern -eq "" ) { $pattern = Read-Host "Enter the text to search for, e.g. 'Joe' " }
if ($replacement -eq "" ) { $replacement = Read-Host "Enter the text to replace with, e.g. 'J' " }
if ($filePattern -eq "" ) { $filePattern = Read-Host "Enter the file search pattern, e.g. '*.c'" }
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
2024-10-01 13:37:53 +02:00
"✅ Replaced '$pattern' by '$replacement' in $($files.Count) files in $($elapsed)s."
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
}