Monday, April 9, 2012

Using Powershell to update HOSTS file with IP Address of Server

My development requires me to work on a virtual machine, which has 2 sites hosted via host headers. Unfortunately the IP address changes once in a while when I start up the VM. The normal process goes:
  • On my vm, open cmd
  • Run ipconfig
  • Copy the ip address that starts with 192.168.1.
  • On my host machine, open notepad in administrator mode
  • Open the "HOSTS" file
  • Modify the ip addresses
  • Save

The new process with the PowerShell script:
  • Open PowerShell in Administrator mode
  • Run script
It seems like I should be able to run a script from PowerShell in Administrator mode, but I haven't figured that out yet. Perhaps there is a Windows Explorer context menu modification I can use.

The script gets the IP address of the server and gets the the IP address that I need to use. It proceeds to find and update any existing entries in the HOSTS file and then appends the updated line to the end of the file if it isn't in the HOSTS file.
#
# Modify HOSTS file with updated servers IP address
#

function Main {
 $ipAddrs = [System.Net.DNS]::GetHostAddresses("DEMO-VM-D") | ? { $_.IPAddressToString.StartsWith("192.168.1.") };
 $ipAddr = $ipAddrs.IPAddressToString;
 
 Modify-Host "dev.demo.local" $ipAddr;
 Modify-Host "dev.demo.com" $ipAddr;
}

function Modify-Host($hostDomain, $ip = "127.0.0.1") {
 $hostsPath = "$env:windir\System32\drivers\etc\hosts";
 $hosts = Get-Content $hostsPath;
 $escapedHost = $hostDomain -replace "[.]", "\.";
 $exists = $false;
 $hosts = $hosts | % {if ($_ -match "^\s*((\d{1,3}){3}.*?$escapedHost.*)")
                            {$exists = $true;Write-Host "Updating $hostDomain -> $ip"; "$ip`t$hostDomain";} else {$_}};

 if ($exists -eq $false) {
  Write-Host -NoNewline "Adding $hostDomain to the HOSTS file...";
  $hosts += "$ip`t$hostDomain";
 }
 $hosts | Out-File $hostsPath -enc ascii
 
 Write-Host "Done.";
}
& Main;

No comments: