Search code examples
windowspowershelltime-synchronization

PowerShell: script to check time sync


I need help with checking time sync between Windows servers. Our environment consists of two regions and a mix of domain and workgroup servers. There are multiple child domain controller that the server gets time from, and there's several NTP server that provides time to the workgroup and non windows servers.

I'm thinking to create a script to grab the source output from w32tm like below,

 D:\>w32tm /query /status
 Leap Indicator: 0(no warning)
 Stratum: 6 (secondary reference - syncd by (S)NTP)
 Precision: -23 (119.209ns per tick)
 Root Delay: 0.0407893s
 Root Dispersion: 1.8810856s
 ReferenceId: 0x0A097F3E (source IP:  1.2.3.4)
 Last Successful Sync Time: 24/1/2025 9:15:22 AM
 Source: Child-DC-E.domain.net
 Poll Interval: 10 (1024s)

and then put it into a w32tm query.

 $ntpserver = "Source: Child-DC-E.domain.net"
 w32tm /stripchart /computer:$ntpserver /dataonly /samples:5

Currently I'm stuck at getting the output from $ntpserver because w32tm is not powershell command, so I don't know how to get the output as a string to be used in the next query.

The script will be run the target servers individually by automation tool. We can't use powershell remoting as it's blocked by security. Appreciate if someone can advice or guide me to the right direction.

Thank you in advance.


Solution

  • After googling around, I found this page. Looked at the script and tried out a few lines. Turns out the one below works out for my need.

    PS C:\> $ntpservercheck = w32tm /query /status | Select-String -Pattern '^Source:'
    PS C:\> $ntpserver = $ntpservercheck.ToString().Replace('Source:', '').Trim()
    PS C:\> w32tm /stripchart /computer:$ntpserver /dataonly /samples:5
    Tracking Child-DC-A.domain.net [1.2.3.4:123].
    Collecting 5 samples.
    The current time is 1/27/2025 1:09:57 PM.
    13:09:57, +00.2191678s
    13:09:59, +00.2194472s
    13:10:01, +00.2193648s
    13:10:03, +00.2189340s
    13:10:05, +00.2190456s
    PS C:\>
    

    Thanks for those commented and give advice, appreciate it! =)