Created
August 6, 2018 00:50
-
-
Save smphillips/791e5447423de322d56a2c8173ee93de to your computer and use it in GitHub Desktop.
Powershell to replace URLs in text files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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