Skip to content

Instantly share code, notes, and snippets.

@smphillips
Created August 6, 2018 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smphillips/791e5447423de322d56a2c8173ee93de to your computer and use it in GitHub Desktop.
Save smphillips/791e5447423de322d56a2c8173ee93de to your computer and use it in GitHub Desktop.
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