Рассмотрим ситуацию, когда вам необходимо синхронизировать время вашей Windows машине или Windows сервере с вашим NTP сервером, или внешне доступным сервером времени. Задача простая, но у новичков в системном администрировании это может вызвать некоторые трудности. Так давайте разберемся!
Небольшое отступление: синхронизировать время на всех узлах сети (сервера, рабочие станции, сетевое оборудование, sip телефоны и т.д.) с единым сервером времени является обязательным, для корректной работы всех служб и сервисов в корпоративной сети. Так, например, это необходимо для корректной работы служб Active Directory, контроллеров доменов, почтовых серверов, рабочих станций, обеспечения корректных прав доступа и безопасности.
Операционные системы семейства Windows содержат службу времени W32Time. Эта служба предназначена для синхронизации времени в пределах организации. W32Time отвечает за работу как клиентской, так и серверной части службы времени, причем один и тот же компьютер может быть одновременно и клиентом и сервером NTP (NTP — Network Time Protocol).
Для того чтобы синхронизировать ваш сервер или рабочую станцию вам необходимо выполнить следующие команды, в командной строке (CMD), запущенной от имени администратора:
1. w32tm /query /source – проверяем источник, на который настроена служба времени в данный момент. Вывод команды либо покажет нам имя или адрес существующего ntp сервера, или в случае его отсутствия выдаст “Free-running System Clock”.
2. w32tm /config /syncfromflags:manual /manualpeerlist:”source” – данной командой указываем источник эталонного времени (NTP Сервер) . Заменяем source на ip адрес или на FQDN. В доменной сети стоит указывать адрес контроллера домена. В случае правильности выполнения получим вывод “Команда выполнена успешно”.
3. w32tm /config /update – обновляем службу времени, чтобы новые настройки применились.
4. w32tm /resync – запускаем принудительное обновление с новым сервером времени.
Все. Вы синхронизировали службу времени на вашей машине с внешним источником. Данный подход позволит вам добиться того, что все машины в вашей сети будет иметь единое правильное время, что позволит избежать ряда сбоев из за расхождения во времени.
Дополнительные команды управления службой времени:
w32tm /query /source — выводит источник времени, на который настроена служба Windows Time
w32tm /monitor — при запуске на контроллере домена (КД) показывает, насколько отличается время на других КД и на внешнем источнике времени, на который настроен PDC
w32tm /config /syncfromflags:manual /manualpeerlist:ru.pool.ntp.org — настройка в качестве источника времени пула ntp-серверов ru.pool.ntp.org
w32tm /config /update — эту команду необходимо выполнить, чтобы служба времени применила новые настройки
w32tm /resync — выполнение синхронизации времени
w32tm /unregister — отменяет регистрацию службы и удаляет настройки из реестра
w32tm /register — регистрирует службу и восстанавливает настройки по умолчанию
Материал из support.qbpro.ru
Скрипт для синхронизации времени в Windows:
net time /setsntp:10.10.5.1 net stop w32time && net start w32time net w32tm /resync
или
net w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:manual /update
Запуск от имени Администратора:
runas /user:Администратор "cmd /C net time /setsntp:10.10.5.1 && net stop w32time && net start w32time && w32tm /resync"
Изменение времени в CMD
- Пример скрипта:
runas /user:127.0.0.1\Администратор "cmd /C w32tm /config /syncfromflags:manual /manualpeerlist:pool.ntp.org && w32tm /config /update"
или
echo password|runas /netonly /user:127.0.0.1\Администратор "cmd /A /C chcp 866>nul time net time /setsntp:pool.ntp.org w32tm /config /syncfromflags:manual /manualpeerlist:pool.ntp.org net stop w32time && net start w32time w32tm /config /update pause "
- Пример команды если компьютер в домене:
runas /user:127.0.0.1\Администратор "cmd /A /C w32tm /config /syncfromflags:manual /manualpeerlist:pool.ntp.org && w32tm /config /update"
- Отключение автоматического перехода на летнее/зимнее время» из пользователя с ограниченными правами:
runas /user:127.0.0.1\Администратор "cmd /A /C regedit"
Ищем в реестре:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation]
создаем ключ DWORD спараметром «1»:
DisableAutoDaylightTimeSet = 1
Время в командной строке
Пример:
runas /user:127.0.0.1\Администратор "cmd /A /C time 21.45"
Time — задает системное время
Выводит и задает системное время.При использовании без параметров, команад time отображает системное время и предлагает
ввести новое время.
Синтаксис time [/t] [/time] [часы:[минуты[:секунды[.сотые]]][{A|P}]]
Параметры
/t
Выводит на экран текущее системное время без предложения ввода нового.
/time
Такой же как параметр /t.
часы
Задает значение часов. Допустимы величины от 0 до 23.
минуты
Задает значение минут. Допустимы величины от 0 до 59.
секунды
Задает значение секунд. Допустимы величины от 0 до 59.
сотые
Задает значение сотых долей секунды. Допустимы величины от 0 до 99.
{A|P}
Задает время до полудня (A.M.) или после полудня (P.M.) для 12-часового формата времени.
Если указано допустимое 12-ти часовое значение, но не задано значение A или P, команда time использует A (до полудня).
/?
Отображает справку в командной строке.
- Пример скрипта синхронизации для Windows Server 2008
@echo off w32tm /config /manualpeerlist:0.pool.ntp.org,0x1 /syncfromflags:MANUAL net stop w32time net start w32time net w32tm /resync
ИСТОЧНИКИ
взято тут
The other day I got a client asking for help syncing time across all Windows 10 thin clients with their NTP server. After taking a walk around NYC and witnessing many hanging shoes I refreshed my head I found a useful way to check Windows NTP configuration using the command prompt.
Using w32tm To Check and configure NTP using the Command Prompt
In Windows 10 open your command prompt and type the below command to check your current NTP configuration:
w32tm /query /configuration
The above gives you the current time configuration.
w32tm /query /status
The above shows you many more details, such as: stratum, precision, last sync, NTP server and etc..
time /T
This last one shows the current time.
At some Windows10 machines I got the below error:
The following error occurred: The service has not been started. (0x80070426)
This means the time service has is not running or disabled. I made sure to enabled accordingly either using the command prompt:
net start w32time
or at the services window when the above did not work:
There’s also a way to set and start Windows NTP configuration using the command prompt this way:
w32tm /config /manualpeerlist:10.0.0.5 /syncfromflags:manual /reliable:yes /update
Then, as usual Windows stays problematic. I had to run the below commands in sequence:
w32tm /unregister
w32tm /register
net start w32time
I did all these because I found out by running:
net time /querysntp
I got the deprecated error:
The /QUERYSNTP and /SETSNTP options have been deprecated. Please use w32tm.exe to configure the Windows Time Service.
At the end of the config you might need to run:
w32tm /config /update
w32tm /resync /rediscover
To make Windows 10 rediscover its NTP settings. Play around, research the official Windows documentation. You can also place all these command on a batch file and deploy it to all your clients.
Good luck! Contact me if you have any questions. Remember to check out my IT Handyman shop for cool T-Shirts and coffee mugs I designed once in a while.
The benefits of your Windows computer clock transcend way beyond just telling the time. It needs to be accurate at all times else some apps and programs might not work properly. To ensure that your computer’s clock is always accurate, Windows has a dedicated ‘Time Service’ that syncs your PC’s time to Microsoft’s internet server. Although this synchronization process happens automatically, we’ll show you how to get it done manually and fix issues with syncing system time.
If your computer’s time is incorrect, it most likely isn’t synced with the Windows or Microsoft Time server. In this post, we will show you how to synchronize your Windows PC time with the Microsoft server. Also, how to fix some time synchronization issues. Let’s go.
From Windows Settings
One of the easiest ways to sync Windows PC’s time with the Microsoft server is syncing it manually from the Windows Settings menu. Follow the steps below to get it done.
Step 1: Tap the Windows key + I button simultaneously on the keyboard to launch the Windows Settings menu.
Step 2: Select ‘Time & Language’.
Step 3: In the ‘Date & Time’ section, navigate to scroll down to the ‘Synchronize your clock’ sub-section and tap the ‘Sync now’ button.
That will immediately sync your computer’s clock with the Microsoft time server (usually takes 2 – 5 seconds).
Note: According to Microsoft, it is impossible to guarantee time accuracy on computers that have intermittent or no network connections. Therefore, you should have an active internet connection to effectively sync your computer’s time to the Microsoft Time Server.
It is also important to state that Windows automatically synchronizes your PC’s time with the Microsoft server daily. In the case where you need to manually sync the time, perhaps because your computer’s time configuration is incorrect, you can use the Sync now button in Step 3 above.
Restart the Windows Time Service
Restarting the Windows Time Service from the Windows Services Manager is an another effective way to sync your PC’s clock with the Windows server. For context, the Windows Time Server helps Windows users to maintain the most accurate time on their devices by syncronizing date and time information with the Microsoft Time server actively.
If your computer faces issues with incorrect timing or is always going out of sync with the official Microsoft server, then there might be a problem with the Windows Time service and restarting it could help. Here’s how to get it done.
Step 1: Tap the Windows key + R key simultaneously on your keyboard to launch the Run command dialog box.
Step 2: Type services.msc into the provided box and tap the OK button.
That will launch the Windows Services Manager in a new window. Scroll to the bottom of the page and locate Windows Time services on the page are arranged alphabetically so you shouldn’t have a problem locating it.
Next, enable this service or confirm that it is enabled and functioning properly. Because as Windows warns, date and time synchronization will be unavailable if the Windows Time service is stopped or disabled.
Step 3: Right-click on the Windows Time service and select Start.
If the Windows Time service was enabled and functioning but your PC’s time is still incorrect or not synced to the Microsoft time server, then you should restart the service. Right-click on Windows Time and select Restart.
Step 4: Restart your computer.
Upon restart, you want to also ensure your device is connected to an active internet (Wi-Fi or Ethernet cable) connection.
Re-Register Windows Time DLL file
Some apps and services on Windows make use of Dynamic Link Library (DLL) files to effectively execute their functions and activities. The DLL file responsible for the Windows Time service (W32Time) is the w32time.dll file. If this file goes missing, gets deleted, or corrupted, you might have issues synchronizing your computer’s time with the Windows server.
Re-registering the w32time.dll would help ensure your PC is regularly synced. Here’s how to register it on your PC.
Step 1: Tap the Windows key + X button simultaneously on your keyboard to launch the Windows Quick Access menu.
Step 2: Select ‘Command Prompt (Admin)’.
Step 3: Type in the command below into the Command Prompt console and hit the Enter button.
regsvr32 w32time.dll
In less than a minute, you should see a notification that the w32time.dll was successfully registered on your PC.
Step 4: Restart your computer and check to see if your PC’s time is now accurate and syncs correctly with the Microsoft server.
Note: Make sure your computer is connected to an active internet connection.
Replace CMOS battery
If you are sure everything is good with your computer’s Windows Time services and syncing configuration but the time and date remain inaccurate or often go out of sync particularly after a system reboot, there’s a high chance that your PC’s CMOS (Complementary Metal Oxide Semiconductor) battery is faulty.
The CMOS chip is located on the motherboard. It keeps your PC’s time and date, as well as other configurations, up-to-date every time you turn off your computer. For that, the CMOS chip has its dedicated battery. If that battery is faulty or damaged, your PC’s time and date will always be messed up, so will its syncing with the Microsoft server.
Replacing the CMOS battery requires some technical know-how and expertise. Thatis why we recommend taking your PC to a skilled technician or the manufacturer’s official repair center.
Stay in Sync
Having incorrect system time on your PC could result in network and connectivity issues, file management problems, and difficulties using some apps and programs. The Microsoft time server is always accurate hence you should ensure that your PC is synced with it.
Next up: Can’t keep up with the time differences between several countries? Adding multiple clocks to your Windows PC could help. Check out two ways to get it done in the article below.
Was this helpful?
Thanks for your feedback!
The article above may contain affiliate links which help support Guiding Tech. The content remains unbiased and authentic and will never affect our editorial integrity.
Windows computers must have their time synchronized with the domain in order to function properly in Active Directory. If the time on a client computer is out of sync with the domain, this can cause a number of problems. The most critical are related to the failure of Kerberos authentication and access to the resource if the time on a client computer is more than 5 minutes off from the domain controller.
In this post we’ll cover how to sync time on a client device with the AD domain and how to troubleshoot when things go wrong.
Understanding the Time Hierarchy in the Active Directory Domain
By default, all domain-joined computers automatically sync their time with the domain controller according to the strict Active Directory domain hierarchy.
- Workstations and member-servers use their authenticating Domain Controller (LogonServer) as the time source (in accordance with AD sites and subnets configuration);
- All domain controllers sync their time DC holding the PDC Emulator FSMO role;
- The PDC synchronizes the time with an external reliable time source (NTP server). The domain controller with the PDC role is the main source of time in the domain.
- In a multi-domain AD forest, the PDC emulator in each domain sync its time with the PDC in the forest root domain.
Hint. Learn more about time syncing in an Active Directory domain using the GPO.
Sync Time with DC on the Domain-Joined Machine
By default, Windows computer should automatically synchronize its time with the nearest domain controller when it joins a domain. In most cases, no additional manual action is required to sync the time with domain.
On a Windows 10/11 computer, check the current time source and sync status. Go to Settings > Time and Language > Date & time > Additional settings and make sure your DC is used as the last time sync source.
There is no graphical interface for managing the Windows Time service (W32Time), so it can be configured from the command line (w32tm command), from the registry (HKLM\System\CurrentControlSet\Services\W32Time\Parameters), or via Group Policy.
To check and configure the time sync settings from the command prompt, use the w32tm command. Get the current time source on a computer:
w32tm /query /source
This command should return the name of one of the AD domain controllers on a domain-joined machine:
View the detailed time setting and last sync time:
w32tm /query /status
Force a time sync with DC:
w32tm /resync /rediscover
If the time synchronization is successful, Event ID 37 should appear in the Event Viewer with the Time-Service source:
The time provider NtpClient is currently receiving valid time data from dc01.theitpro.loc (ntp.d|0.0.0.0:123->192.168.8.10:123).
Make sure that the computer is configured to automatically synchronize its time according to the domain hierarchy:
w32tm /query /configuration
Scroll down to the [TimeProviders] sections and ensure that the Type is set to NTDS5. If not, this may be the cause of time sync problems on a computer.
This value can also be found in the Type parameter under the registry key HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters. The NtpServer value is ignored when NTDS5 is used.
To re-enable time synchronization with a DC for computers in an Active Directory domain
w32tm /config /syncfromflags:domhier /update net stop w32time && net start w32time
This will reset the time sync settings back to NT5DS. This means that the machine should find a time server in the Active Directory hierarchy.
If the Windows client fails to synchronize time with the AD domain controller, you must to reset the Windows Time service configuration.
Unregister w32time service and remove settings:
w32tm /unregister
Register the w32tm service and restore the default settings:
w32tm /register
Enable time sync with AD:
w32tm /config /syncfromflags:domhier /update
Restart the service:
net stop w32time && net start w32time
Update settings:
w32tm /config /update
Synchronize the time:
w32tm /resync
Check the new time sync settings:
w32tm /query /status
Time Sync Issues on Windows Domain Joined Computers
The Windows Time Service (W32Time) is responsible for time synchronization. Check that this service is running on a client with Get-Service:
Get-Service W32Time | Select-Object name,status
UDP port 123 is used for time synchronization on Windows. If the port is closed, the w32tm /resync command will return an error:
Sending resync command to local computer
The computer did not resync because no time data was available.
In this case, the following entry appears in the Event Viewer log:
EventID: 129
Source: Time-Service
NtpClient was unable to set a domain peer to use as a time source because of discovery error. NtpClient will try again in 15 minutes and double the reattempt interval thereafter. The error was: The entry is not found. (0x800706E1)
Check that the w32time service is running on the DC and listening on UDP port 123:
netstat -an | find "UDP" | find ":123"
Then check that the UDP inbound rule named Active Directory Domain Controller – W32Time (NTP-UDP-In) is enabled in Windows Defender Firewall (Control Panel > Windows Firewall > Advanced settings > Inbound rules).
Or check Windows Defender Firewall rule status with PowerShell:
Get-NetFirewallrule -DisplayName 'Active Directory Domain Controller - W32Time (NTP-UDP-In)'|select Enabled
If the rule is disabled, you must enable it:
Get-NetFirewallrule -DisplayName 'Active Directory Domain Controller - W32Time (NTP-UDP-In)'|Enable-NetFirewallrule
It is also possible to force a client to manually synchronize its time with another domain controller.
net time \\ny-dc01 /set /y
Configuring the NTP Client Time Sync on Windows Using GPO
In most cases, time sync with a domain on Windows client doesn’t require administrator intervention. However, if you find that time synchronization is not working properly on client workstations in domain, it is possible to centrally configure client time sync settings using Group Policy.
- Use the gpedit.msc console to change Group Policy settings on a single computer (this is the best solution if you need to solve synchronization problems on a single computer or test new time sync settings). To set up a GPO for multiple domain computers, use the Group Policy Management Console (gpmc.msc);
- Expand the following node in GPO editor: Computer Configuration > Administrative Templates > System > Windows Time Service;
- Enable the Enable Windows NTP Client policy;
- Then enable the Configure NTP Client policy and set the following settings in the Options panel:
NTPServer: your domain name (preferred) or FQDN name of the domain controller with the PDC Emulator role (you can find it with the command: netdom.exe query fsmo)
Type: NT5DS
CrossSiteSyncFlags: 2
ResolvePeerBackoffMinutes: 15
ResolvePeerBackoffMaxTimes: 7
SpecialPollInterval: 64
EventLogFlags: 0 - Restart your computer to apply the new GPO client time settings.
Cyril Kardashevsky
I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
