Using PowerCLI to update DNS settings on VMware hosts

There nothing like an outage that causes you to double check settings across the environment. Rewind to a week ago, and that was the outage that caused doublechecking the DNS settings on everything that has DNS settings. So as the good VMware admin that I am, I wrote a quick one-liner to pull all of the DNS settings for the hosts in both of my vCenters.

Get-VMhost | Foreach { $_ | Select Name, @{N="DNSAddress";E={($_ | Get-VMhostNetwork).DNSAddress -join "," }} }

This one-liner just displays the information to the console for review. If needed, you can append the line with the code to save to a CSV.

Get-VMhost | Foreach { $_ | Select Name, @{N="DNSAddress";E={($_ | Get-VMhostNetwork).DNSAddress -join "," }} }  | export-csv C:\Scripts\Logs\VMhost_DNS_Settings.csv -NoTypeInformation

Once I reviewed the output of the DNS settings, I then wrote a script that would remove the unwanted DNS servers, and verify or add the needed ones.

$VMhosts = Get-VMhost

Foreach ($VMhost in $VMhosts){
    $Esxcli = Get-EsxCli -VMHost $VMhost -V2
    $DNS = ($esxcli.network.ip.dns.server.list.Invoke()).DNSServers
    IF (!($DNS -contains "192.168.0.1")){ $esxcli.network.ip.dns.server.add.Invoke(@{server='192.168.0.1'}) }
    If (!($DNS -contains "192.168.0.2")){ $esxcli.network.ip.dns.server.add.Invoke(@{server='192.168.0.2'}) }
    
    $DNS = ($esxcli.network.ip.dns.server.list.Invoke()).DNSServers
    If ($DNS -contains "192.168.1.1"){ $esxcli.network.ip.dns.server.remove.Invoke(@{server="192.168.1.1"}) }
    If ($DNS -contains "192.168.1.2"){ $esxcli.network.ip.dns.server.remove.Invoke(@{server="192.168.1.2"}) }
    If ($DNS -contains "192.168.2.1"){ $esxcli.network.ip.dns.server.remove.Invoke(@{server="192.168.2.1"}) }
    If ($DNS -contains "192.168.2.2"){ $esxcli.network.ip.dns.server.remove.Invoke(@{server="192.168.2.2"}) }
}

So what this script does is it looks to see if the configured DNS doesn’t contain the ideal DNS servers, it then adds them. Then it looks at to see if any of the other known bad DNS servers are configured and removes them.

-Stuart

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.