PowerCLI ESXi NTP Service Query

Last week, I was asked to write up a script to check the NTP settings across all ESXi servers. The script had to output:

    • Cluster
    • ESXi
    • IP Address (NTP server)
    • Policy
    • Running

It looked very straightforward but one thing wasn’t clear. During scripting, I found that the policies Get-VMHostService -VMHost <VMHost[]> | %{$_.Policy} returns were:

    • On
    • Off
    • Automatic

So that the output looked like:

Cluster     : cluster1
ESXi        : esxi1.test.com
NTP Server  : ntp.test.com
Service     : NTP Daemon                  
Policy      : on                          
Running     : True

For the policy, on, off and automatic means nothing to the end-users, needed more explanations. After digging in, I discovered the following:

    • On =>  Start and stop with host
    • Off => Start and stop manually
    • Automatic => Start automatically if any ports are open, and stop when all ports are closed

Hence, I used a simple switch command to translate the above:

switch ($policy) { 
  "off" { "Start and stop manually"} 
  "on" { "Start and stop with host" } 
  "automatic" { "Start automatically if any ports are open, and stop when all ports are closed" }
}

And the final script is:

Function NTP-Query
{
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true)]
    [string]$cluster
  )

  foreach ($esxi in (Get-Cluster -Name $cluster | Get-VMHost | Sort Name)) {         
    $service = Get-VMHostService -VMHost $esxi | Where {$_.Key -eq "ntpd"}
    $policy = switch ($service.Policy) { 
                "off" { "Start and stop manually"} 
                "on" { "Start and stop with host" } 
                "automatic" { "Start automatically if any ports are open, and stop when all ports are closed" }
              }
    $ntp = Get-VMHostNtpServer -VMHost $esxi
    $esxi | Select-Object @{N="Cluster";E={$_.Parent}}, 
                          @{N="ESXi";E={$_.Name}}, 
                          @{N="NTP Server";E={$ntp}}, 
                          @{N="Service";E={$service.Label}}, 
                          @{N="Policy";E={$policy}},
                          @{N="Running";E={$service.Running}}
  }
}

Hope this helps to those of you writing a script to check NTP settings as well as the service policy.

Advertisement

One thought on “PowerCLI ESXi NTP Service Query

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s