There's no doubt that time is critically important in a computing
environment. Given this sensitivity, and the recent recognition that we
had rogue hosts improperly configured, I decided to crank out a script
that would analyze our environment. I wanted to find whether the NTPD
service was running, what the NTP server configuration was, and provide
a report of this. Additionally I wanted to have the option (with
commenting) to automatically make corrections.
Always open to suggestions and improvements. I hope this helps you in your environment.
###----
FULL SCRIPT
#####
Connect-VIServer -Server server.domain.com #Enter your vCenter Server
$NtpServer = "10.10.10.10" #Provide your default NTP Server. This will be used as default so entering a NTP server when prompted is not necessary
$OldNtpServer = "10.10.10.11" #Leave set as 127.127.1.0 as default unless you wish to change settings in your environment
$DefaultNtpServer = "127.127.1.0" #NTP Server Value that is set on a fresh ESX installation.
#Location based on Date
$date = Get-Date -UFormat %Y%m%d
$ExportLocation = "C:\NTP-$date.csv"
#Location where you would like report to be saved to.
#$ExportLocation = 'C:\NTPReport.csv'
$NTPHosts
= Get-VMHost | Select-Object Name,@{Name="NTPServer";Expression={$_ |
Get-VMHostNtpServer}}, @{Name="NTPRunning";Expression={($_ |
Get-VMHostService | Where-Object {$_.key -eq "ntpd"}).Running}} |
Sort-Object -Property "NTPRunning", "NTPServer"
$NTPHosts | Export-Csv $ExportLocation -NoTypeInformation
& $ExportLocation #Opens generated report file
$Restart = Read-Host "Would you like to start NTPD services or change NTP configurations on hosts? (y/n)"
#$Restart = "y" #Comment above line and uncomment this line if you wish to automatically restart services.
If ($Restart -eq "y"){
Import-Csv $ExportLocation | % {
$vmhost = $_.Name
#Checks the NTP configuration against a value previously determined at the top of script.
If (($_.NTPServer -eq $OldNtpServer) -or ($_.NTPServer -eq $DefaultNtpServer)){
$NtpInput
= Read-Host "Some servers are configured with NTP set as $OldNtpServer
or $DefaultNtpServer and may need their NTP settings reconfigured.
Please enter NTP Server FQDN or IP address. <$NtpServer> is
default."
If ($NtpInput -ne "") {
$NtpServer = $NtpInput
#Sets $NtpServer to the inputted value and does nothign if left blank.
This allows use of default when value is consistent in the environment.
}
Add-VMHostNtpServer -VMHost $vmhost -NtpServer $NtpServer | Where-Object {$_.NTPServer -eq $OldNtpServer}
Remove-VMHostNtpServer -VMHost $vmhost -NtpServer $OldNtpServer
}
#Now time to restart any NTPD services that are currently not running.
If ($_.NTPRunning -eq "False") {
Get-VmHostService -VMHost $vmhost | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService
}
}
}
Write-Host "Process Complete"