ESXCLI - Update Host DNS
Need to update DNS servers on a bunch of hosts?
If you ever find yourself in a position where you need to update DNS on a bunch of hosts, this might get the job done.
It's fairly straight forward. First get the vCenter and do no validation, connect to said vCenter, get a list of all hosts, then strip all DNS servers and add the ones desired back in.
What makes this ugly?
There's no input validation
There's no function to make this more portable
It doesn't care what DNS is there, it just obliterates it.
New DNS values are hardcoded.
# Set the vCenter we are connecting to
$vCenter = read-host 'vCenter FQDN'
# Connect to vCenter
Connect-VIServer -Server $vCenter
# Build a list of all hosts in $vCenter
$vmHosts = (Get-VMHost)
# Run the following on all $vmHosts connected to $vCenter one at a time
foreach ($vmHost in $vmHosts) {
# Instantiate an ESXiCLI object for $vmHost
$esxcli = Get-EsxCli -VMHost $vmHost -V2
# Build ESXiCLI argument object and invoke $esxcli to remove exsisting DNS hosts
$argument = $esxcli.network.ip.dns.server.remove.CreateArgs()
$argument.all = $true
$argument = $esxcli.network.ip.dns.server.remove.Invoke($argument)
# Build ESXiCLI argument object and invoke $esxcli to add new DNS hosts
$argument = $esxcli.network.ip.dns.server.add.CreateArgs()
$argument.server = '123.123.123'
$argument = $esxcli.network.ip.dns.server.add.Invoke($argument)
# Build ESXiCLI argument object and invoke $esxcli to add new DNS hosts
$argument = $esxcli.network.ip.dns.server.add.CreateArgs()
$argument.server = '123.123.24'
$argument = $esxcli.network.ip.dns.server.add.Invoke($argument)
}
How can we make this better?
Make it into a function
Add parameters
Add input validation
Make it a Function
Let's start with making it an advanced function. To do this we need to give it a name using approved verbs. I'll use Set-vmHostDNS.
Function Set-vmHostDNS {
[CmdletBinding()]
Param ()
# Code goes here
}
Great, now we can import our .ps1 file and use Set-vmHostDNS to run our script. That's neat but not super helpful by itself. Lets add some parameters to our function. This is where we can add a ton of flexibility like specifying the host we want to update or specifying the DNS we want to use. For this we will be looking at the new para () block.
Parameters are defined using [Parameter()]$paramName