Notes of a scripter

PowerCLI to Update VMHost Name

What’s your (host)name?

While digging through Log Insight on a problem, I found a new one.  A large majority of VMhosts were not configured with a proper hostname.  This was also backup by the vCheck report that gets generated weekly.  The hosts were configured with ‘localhost’ as the hostname, which makes this a huge pain when trying to follow the logs.

vRealize Log
vRealize Log showing localhost

So as seen above in the image there are 4,046,800 events that have generated from the hostname, ‘localhost’.  How would I find the event I needed from this to troubleshoot any issues with these falsely named host.

Hello My Name is…

After talking with another engineer on my team, he told me that every way that he saw to fix this was a reboot, and I didn’t like that answer.  So I took to PowerCLI to get the hostname and see how to update it.

$hostname = Get-vmhost "VMhostName"
$esxcli = Get-esxcli -vmhost $hostname
$esxcli.system.hostname.get()

This will display the currently configured domain name, fully qualified domain name, and hostname as shown below.

Results of esxcli.system.hostname.get()

So getting the configured hostname is simple.  The same is true with setting the correct hostname, as its all in the syntax.

$DomainName = "Domain.com"
$name = "VMhostName"
$esxcli.system.hostname.set($DomainName,$null,$name)

So the syntax here was a bit tricky, you would think that all of the fields would need to be populated, but that isn’t correct.  You will only need to put the values in for the domain name and hostname.  ESXi is smart enough to put them together for the FQDN.

Updated hostname with Esxcli

Loop it

So in my case I have about 50 hostname that need updated.  So lets just put this script into a foreach loop.

I put all of the FQDNs of the hostnames into a text file so I can grab one at a time and then format the data correctly to be used in the proper syntax of the command.

$hostnames = get-content C:\scripts\logs\VMhostnotmatchhostname.txt

foreach ($hostname in $hostnames){
    $name = $hostname.split('.',2)[0]
    $FQDN = $hostname.split('.',2)[1]
    $vmhost = Get-vmhost $hostname
    $esxcli = Get-esxcli -VMHost $vmhost
    $esxcli.system.hostname.get()
    $esxcli.system.hostname.set($FQDN,$null,$name)
    $esxcli.system.hostname.get()
}

-Stuart

Exit mobile version