Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Powershell to replace URLs in text files
Clear-Host
# TODO: Load this hash table from your CSV source (using Import-Csv)
[hashtable] $urls = New-Object hashtable
$urls.Add("https://www.old.com/1", "https://www.new.com/1")
$urls.Add("https://www.old.com/2", "https://www.new.com/2")
# TODO: Change the -Path value here to the desired path
Get-ChildItem -Path "." -Filter "*.txt" | ForEach-Object {
$modified = $false
Write-Host "Scanning: $_"
$content = Get-Content "$_"
$urls.Keys | ForEach-Object {
if ($content -ilike "*$_*") {
$content = $content -ireplace $_, $urls[$_]
$modified = $true
}
}
if ($modified) {
# Make a backup copy of the file
Copy-Item -Path $_ -Destination "$_.bak"
# Replace the contents
$content | Set-Content -Path $_ -ErrorAction Stop
Write-Host "...Updated: $_"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment