Skip to content

Replace-InFiles

Search and replace a pattern in the given files by the replacement

param([string]$pattern = "", [string]$replacement = "", [string]$filePattern = "")

function ReplaceInFile([string]$path, [string]$pattern, [string]$replacement) {
    [System.IO.File]::WriteAllText($path,
        ([System.IO.File]::ReadAllText($path) -replace $pattern, $replacement)
    )
}

try {
	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'" }

	$stopWatch = [system.diagnostics.stopwatch]::startNew()
	$files = (Get-ChildItem -path "$filePattern" -attributes !Directory)
	foreach($file in $files) {
		ReplaceInFile $file $pattern $replacement
	}
	[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
	"? Replaced '$pattern' by '$replacement' in $($files.Count) files in $($elapsed)s."
	exit 0 # success
} catch {
	"?? ERROR: $($Error[0]) (script line $($_.InvocationInfo.ScriptLineNumber))"
	exit 1
}

Specifies the text pattern to search for (ask user by default)

Specifies the text replacement (ask user by default)

Specifies the file search pattern (ask user by default)

An interactive directory of PowerShell scripts.