Advertisement

Sync time on Windows startup

Zeynel -
6 hours ago

There are some rare circumstances that you may want to re-sync your time on Windows startup. One of these can be a depleted CMOS battery on your laptop or desktop computer: This will cause the time to be at least “inaccurate”.

While Windows sync date and time in some interval, it doesn’t check the system date and time specifially on system startup. So you need to do it yourself by going Date and Time in Windows Settings, and clicking “Sync now”.

Of course if the problem is the CMOS battery, the proper solution is to replace it. But if you can’t do it for some reason, or you need a solution until you do, here it is.

PowerShell script to sync time at startup

This script isn’t developed by me, it’s by AI but it’s tested and I've added features to make it run (hopefully) without problems:

  • The script waits for the internet connection for 15 minutes before failing.
  • Tries alternative NTP server if main one fails.
  • Writes last operation to a log file in same folder with script file.
  • Checks if Windows Time service is available, and starts it if it is not.

When you run it with via Task Manager as admin, you can see if it’s working last lines in the mentioned Sync-Time.log.

Save this code as Sync-Time.ps1 (e.g. by creating empty file in Notepad).

# Define NTP servers to try
$NtpServers = @("time.windows.com", "pool.ntp.org", "time.google.com")
$MaxWaitMinutes = 15
$WaitInterval = 10  # Check every 10 seconds
$ServiceWaitSeconds = 30  # Time to wait for w32time service
 
# Determine the script directory and log file path
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$LogFile = Join-Path $ScriptDir "Sync-Time.log"
 
# Function to write log
function Write-Log {
    param ($Message)
    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$Timestamp - $Message" | Out-File -Append -FilePath $LogFile
}
 
# Ensure the Windows Time service is running
Write-Host "Checking Windows Time Service..."
Write-Log "Checking Windows Time Service..."
$Service = Get-Service -Name w32time -ErrorAction SilentlyContinue
 
if ($Service -eq $null) {
    Write-Host "Windows Time service is not installed! Exiting."
    Write-Log "Windows Time service is not installed! Exiting."
    Start-Sleep 2
    exit
}
 
if ($Service.Status -ne "Running") {
    Write-Host "Starting Windows Time Service..."
    Write-Log "Starting Windows Time Service..."
    Start-Service w32time
    Start-Sleep -Seconds $ServiceWaitSeconds  # Allow time for service to start
}
 
# Wait for internet connection
$StartTime = Get-Date
Write-Host "Waiting for internet connection..."
Write-Log "Waiting for internet connection..."
while (-not (Test-Connection -ComputerName "8.8.8.8" -Count 1 -Quiet)) {
    if ((New-TimeSpan -Start $StartTime).TotalMinutes -ge $MaxWaitMinutes) {
        Write-Host "Internet not available after $MaxWaitMinutes minutes. Exiting."
        Write-Log "Internet not available after $MaxWaitMinutes minutes. Exiting."
        Start-Sleep 2
        exit
    }
    Start-Sleep -Seconds $WaitInterval
}
 
Write-Host "Internet is available. Syncing time..."
Write-Log "Internet is available. Syncing time..."
 
# Try each NTP server
foreach ($Server in $NtpServers) {
    Write-Host "Trying NTP server: $Server"
    Write-Log "Trying NTP server: $Server"
    try {
        w32tm /config /manualpeerlist:$Server /syncfromflags:manual /update | Out-Null
        w32tm /resync | Out-Null
        Start-Sleep -Seconds 1
        $Status = w32tm /query /status
        Write-Host "Time synchronized successfully with $Server"
        Write-Log "Time synchronized successfully with $Server`n$Status"
        Start-Sleep 2
        exit
    } catch {
        Write-Host "Failed to sync with $Server. Trying next..."
        Write-Log "Failed to sync with $Server. Trying next..."
    }
}
 
Write-Host "All NTP servers failed. Time sync unsuccessful."
Write-Log "All NTP servers failed. Time sync unsuccessful."
Start-Sleep 2

 Now, open the Task Manager and create a task as follows:

  • Click Create a Basic task

   Under General:

  • Name: Sync Time at Startup
  • Run with highest privileges:(Check this)
  • Configure for: Windows 10/11

   Under Triggers:

  • Click New...
  • Choose "At startup"
  • Check "Delay task for" → Set to 1 minute
  • Check "Repeat task every" → Set to 30 minutes (Optional)
  • Click OK

   Under Actions:

  • Click New...
  • Program/script: powershell.exe
  • Arguments (edit the directory to actual location you saved the script):

-ExecutionPolicy Bypass -File "C:\Scripts\Sync-Time.ps1"

  • Click OK

   Under Conditions:

  • Uncheck "Start the task only if the computer is on AC power"

   Under Settings:

  • Check "If the task fails, restart every" → Set to 1 minute, up to 3 attempts

   Click OK, enter your admin password if prompted. 

That’s it. Now you can restart the computer to see if it works. After system restart, check the log file created in the same folder with the .ps1 file we created. If it’s working, the last line will look like:

2025-03-05 13:19:28 - Time synchronized successfully with time.windows.com
Leap Indicator: 0(no warning) Stratum: 4 (secondary reference - syncd by (S)NTP) Precision: -23 (119.209ns per tick) Root Delay: 0.3442501s Root Dispersion: 9.9794729s ReferenceId: 0x682895BD (source IP:   104.40.149.189) Last Successful Sync Time: 5.03.2025 13:19:27 Source: time.windows.com  Poll Interval: 10 (1024s) 

Troubleshooting

If for some reason the script is failing, try these commands. 

- Force Windows to use NTP sync consistently:

sc config w32time start=auto

w32tm /config /manualpeerlist:"pool.ntp.org,time.google.com,time.windows.com" /syncfromflags:manual /update

w32tm /resync

Conclusion

Enjoy your always up-to-date time. When you solve the problem, you can remove it from Task Manager or disable the task to remove unnecessary task at startup. 

 

Did you find this article useful?
0 0
Share this page on:



Only registered users can post links.
Checking site status...
 
No comments yet. Ask, or type the first one!