Change Hosts File with Powershell on many Servers

Don’t change hosts file, until you really must!

  1. First you need script to change hosts file locally (EditHosts.ps1)

$hostsPath = “$env:windir\System32\drivers\etc\hosts”
$hosts = get-content $hostsPath
$ip = (get-wmiobject win32_NetworkAdapterConfiguration -filter “IPEnabled=True”).IPAddress
$a=%{$ip}
$string = $a + ”       bla.bla.com”
$hosts = $hosts + $string
$hosts | Out-File $hostsPath -enc ascii

2.Create text file with server names if you want to bulk change on many servers

### TXT File ####
Servers
ChicagoSRV
LondonSRV
FrankfurtSRV
 ################

3.Now you need script to invoke your script on remote systems

$Servers=import-csv test.txt
$i=1
foreach($cas in $servers)
{
$a=$cas.servers
write-host “$i”
write-host “$a”
Invoke-Command -ComputerName $a -FilePath “C:\EditHosts.ps1”
$i=$i+1
}

4. Done…

This entry was posted in Uncategorized. Bookmark the permalink.

1 Response to Change Hosts File with Powershell on many Servers

  1. Matthias says:

    This helps us out of changing one by one. Nice little script that gives you all the options we need. And the best we can do this by powershell automaton.Thanks a lot!

Leave a comment