Summary

Quick script I made to update hosts file entry. What it does is that it comments out previous IP and domain name and creates new a new line with the new IP and domain name. It was challenging in that the number of spaces and tabs might be different and we do not know what was entered in the hosts file.

 

$domainNameToBeUpdated = “test.com”
$newEntry = “127.0.0.1 newtest.com #updated 3/22/16”
$commentOutOldEntries = Get-Content $hostsFile | Select-String $domainNameToBeUpdated | Foreach-Object{ If($_ -Match $domainNameToBeUpdated ){‘#’ + $_ + ‘ #OLD Entry 1/1/16’} }
$hostsFile = “C:\Windows\System32\drivers\etc\hosts”
$oldEntries = Get-Content $hostsFile | Select-String $domainNameToBeUpdated
Write-host $oldEntries
foreach( $oldEntry in $oldEntries)
{
foreach ($commentOutOldEntry in $commentOutOldEntries)
{
(Get-Content $hostsFile) -replace $oldEntry, “$commentOutOldEntry `n$newEntry” | Set-Content $hostsFile
}
}