# ============================== # Windows Time Sync - Smart MSP Version # ============================== function Ensure-Admin { if (-not ([Security.Principal.WindowsPrincipal] ` [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host "āŒ Please run as Administrator!" -ForegroundColor Red exit } } function Restart-TimeService { Stop-Service w32time -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 Start-Service w32time } function Repair-TimeService { Write-Host "šŸ›  Repairing Windows Time Service..." -ForegroundColor Yellow Stop-Service w32time -Force -ErrorAction SilentlyContinue w32tm /unregister Start-Sleep -Seconds 2 w32tm /register Start-Service w32time } function Test-DomainReachable { try { $domain = (Get-CimInstance Win32_ComputerSystem).Domain if ($domain -eq $env:COMPUTERNAME) { return $false } nltest /dsgetdc:$domain > $null 2>&1 return $LASTEXITCODE -eq 0 } catch { return $false } } function Sync-Domain { Write-Host "šŸ¢ Attempting Domain Sync..." -ForegroundColor Cyan w32tm /config /syncfromflags:domhier /update Restart-TimeService w32tm /resync /rediscover Start-Sleep -Seconds 3 } function Sync-PublicNTP { Write-Host "šŸŒ Falling back to AU NTP servers..." -ForegroundColor Yellow $ntpServers = "0.au.pool.ntp.org,0x1 1.au.pool.ntp.org,0x1 2.au.pool.ntp.org,0x1" w32tm /config /manualpeerlist:"$ntpServers" /syncfromflags:manual /reliable:NO /update Restart-TimeService w32tm /resync Start-Sleep -Seconds 3 } function Force-HardTimeFix { Write-Host "šŸ’„ Applying HARD fallback (manual correction)..." -ForegroundColor Red try { $ntp = "0.au.pool.ntp.org" $data = w32tm /stripchart /computer:$ntp /samples:1 /dataonly | Select-String ".*" $time = ($data -split ',')[1].Trim() if ($time) { Set-Date -Date $time Write-Host "āœ… Time corrected from NTP server" } else { throw "No time received" } } catch { Write-Host "āŒ Hard correction failed" } } function Validate-Time { $source = (w32tm /query /source) if ($source -match "Local CMOS Clock") { return $false } return $true } function Show-Status { Write-Host "`nšŸ“Š Current Time Status:" -ForegroundColor Green w32tm /query /status Write-Host "" w32tm /query /source } # ============================== # MAIN # ============================== Ensure-Admin Write-Host "==============================" Write-Host " Smart Time Sync Engine" Write-Host "==============================`n" Repair-TimeService $domainOK = Test-DomainReachable if ($domainOK) { Sync-Domain } else { Write-Host "āŒ Domain NOT reachable — switching to NTP" -ForegroundColor Red Sync-PublicNTP } # Validate if (-not (Validate-Time)) { Write-Host "⚠ Still not syncing — retrying with NTP..." -ForegroundColor Yellow Sync-PublicNTP } # Final fallback if (-not (Validate-Time)) { Force-HardTimeFix } Show-Status Write-Host "`nāœ… Time sync process completed." -ForegroundColor Green