Home > Blogs > VMware PowerCLI Blog


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

This entry was posted in ESX, vCenter on by .
Alan Renouf

About Alan Renouf

Alan Renouf is a Product Line Manager at VMware focusing on API's, SDK's and CLI's, He is responsible for providing the architects and operators of private and public cloud infrastructure with the toolkits/frameworks and command-line interfaces they require to build a fully automated software-defined datacenter. Alan is a frequent blogger at http://blogs.vmware.com/PowerCLI a book author and has a personal blog at http://virtu-al.net. You can follow Alan on twitter as @alanrenouf.

2 thoughts on “Updating your hosts file

  1. Deveri Ribakardinad

    good info! definitely will help a lot.

    Reply
  2. Goll

    Cool tip!
    Notes:
    /1 Stop using cmd.exe and use console [http://sourceforge.net/projects/console/%5D
    2/ Stop using notepad and use notepad++ [http://notepad-plus-plus.org/%5D

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*