ESX vCenter

Updating your hosts file

AlanFeb2012_thumb_thumb1_thumb_thumb[2]
Posted by
Alan Renouf
Technical Marketing

How many times have you built a test lab, perhaps you are trying out nested virtualization, which is very cool by the way!

Whilst doing this myself I normally come across an issue where my DNS is not 100% correct, normally I end up editing my hosts file to add entries which define my vSphere hosts just so I can open a console…

Is this a familiar sight ?

TinyGrab Screen Shot 27-06-2012 14.51.12

Whilst doing this recently I had to add a large number of entries to my hosts file so that I could open the console on some of the VMs, as always I found an easy way than manually adding each host reference one by one.  PowerShell.

With the following script I was easily able to pull each host name and IP address and update the hosts file automatically:

The Script

Connect-ViServer MyvCenter

$hostsfilelocation = $env:SystemRoot + "\System32\Drivers\etc\hosts"
$hostsfile = Get-Content $hostsfilelocation
Foreach ($line in (Get-VMHost | Get-VMHostNetworkAdapter -Name vmk0 | Foreach { Write "$($_.IP)`t$($_.VMhost)"})){
    If ($Hostsfile -notcontains $line) {
        $hostsfile = $Hostsfile + $line
        Write-Host "Adding… $line"
    }
}
$hostsfile | Set-Content $hostsfilelocation –Force

In Action

TinyGrab Screen Shot 27-06-2012 15.00.03

Ultimately I ended up with a hosts file which included an entry for each of my hosts and a working console screen !

TinyGrab Screen Shot 27-06-2012 15.01.54

TinyGrab Screen Shot 27-06-2012 15.01.07

Note:  If you have UAC enabled on windows you will need to right click the PowerCLI Icon and choose “Run as Administrator” so it has the permission to edit the hosts file.

I hope this helps anyone who is manually still adding each entry into their hosts file.

Get notification of new blog postings and more by following VMware PowerCLI on Twitter: @PowerCLI