Skip to content

Tag: Service

PowerCLI – Reset NTP settings on VMHosts per Cluster

As daylight savings time is almost upon us, there are always questions revolving around what hosts use what NTP sources for time synchronization. To address this issue, I created a script to go through and remove the current NTP sources, add the desired NTP sources and then restart the NTP service on all of the hosts in the environment. However, to be safe, the preference was that it wasn’t done all at the same time. To achieve this, I broke it down and applied it to hosts one by one in a specified cluster.

When running the script, it will ask for the cluster name and four NTP servers so you don’t have to modify the code unless you want to add more or less NTP servers.


#Reset NTP settings on VM Hosts per Cluster

$InputCluster = Read-Host "Cluster Name:"
$InputNTP1 = Read-Host "First NTP Server:"
$InputNTP2 = Read-Host "Second NTP Server:"
$InputNTP3 = Read-Host "Third NTP Server:"
$InputNTP4 = Read-Host "Fourth NTP Server:"

#Select Cluster to change NTP Settings
$Cluster = Get-Cluster $InputCluster

#NTP servers to be changed to
$ntp1 = $InputNTP1
$ntp2 = $InputNTP2
$ntp3 = $InputNTP3
$ntp4 = $InputNTP4

#Grabbing VMHosts for desired Cluster
$allVMhost = $Cluster | Get-VMHost | sort Name

#Reseting NTP servers one by one
foreach ($vmhost in $allVMhost){

#Remove existing NTP servers
Write-Host "Removing all NTP Servers from $vmhost"
$allNTPList = Get-VMHostNtpServer -VMHost $vmhost
Remove-VMHostNtpServer -VMHost $vmhost -NtpServer $allNTPList -Confirm:$false | out-null
Write-Host "All NTP Servers from $vmhost have been removed"
Write-Host ""

#Setting NTP servers
Write-Host "Adding NTP servers to $vmhost"
Add-VmHostNtpServer -NtpServer $ntp1,$ntp2,$ntp3,$ntp4 -VMHost $vmhost -Confirm:$false | out-null
Write-Host "The following NTP servers have been added to $vmhost : $ntp1, $ntp2, $ntp3, $ntp4"
Write-Host ""

#Checking NTP Service on the ESXi host
$ntp = Get-VMHostService -vmhost $vmhost| ? {$_.Key -eq 'ntpd'}
Set-VMHostService $ntp -Policy on | out-null

if ($ntp.Running ){
Restart-VMHostService $ntp -confirm:$false
Write-Host "$ntp Service on $vmhost was On and was restarted"
}
Else{
Start-VMHostService $ntp -confirm:$false
Write-Host "$ntp Service on $vmhost was Off and has been started"
}

Write-Host ""

}

Click here to download a text file containing the script.

Note: this was a script that worked in my environment. There is no warranty or support with this script, please use at your own risk.