Active Directory это довольно сложная система, даже если ваш домен состоит из двух контроллеров доменов в одном сайте AD. Администратор домена должен уметь быстро проверить состояние контроллеров домена, наличие проблем репликации и исправить найденые проблемы. В этой статье мы рассмотрим типовые команды, которые можно использовать для проверки состояния домена Active Directory и поиска возможных ошибок.
DCDiag – важная утилита для проверки состояния контроллеров домена. Войдите на любой контроллер домена, запустить командную строку и выполните команду:
dcdiag /e /v /q
Это общий тест состояния контроллеров домена и Active Directory. В данном отчете буду указаны только ошибки, которые требует внимание администратора домена.
Затем нужно проверить здоровье DNS серверов (я запускаю эти команды в консоли PowerShell):
DCDiag /Test:DNS /e /v /s:msk-dc01.test.com >c:PSDcdiagDNStest.txt
Затем откройте полученный отчет:
Notepad c:PSDcdiagDNStest.txt
Если со службой DNS нет проблем, то в разделе “Summary of DNS test results” везде должно быть указано PASS.
Если в отчете есть ошибки, нужно исправить их вручную. Если вручную исправить ошибки DNS не удается, попробуйте исправить их автоматически командой dcdiag с параметром fix:
DCDiag /Test:DNS /e /v /s:msk-dc01.test.com /fix
Затем на всех всех контроллерах домена выполните команду:
ipconfig /registerdns
После проверки контроллеров домена и DNS службы нужно проверить состояние репликации Active Directory.
Войдите на любой DC и выполните проверку репликации командой:
repadmin /replsum
Если наибольшее из значений largest delta для любого DC не превышает 1 часа и replication fails = 0, значит в вашем домене нет проблем репликации
Утилиты dcdiag и repadmin доступны на любом DC с ролью ADDS. Если вы хотите использовать эти утилиты в десктопной Windows 10, нужно установить RSAT.
Если вы обнаружили ошибки репликации, можно получить подробную информацию о них командой:
repadmin /showreps
Данная команда покажет какой контекст наименования не реплицируется в AD.
Следующая команда используется для быстрой проверки репликации на конкретном сервере. Если нужно проверить репликацию на всех DCs, используйте параметр wildcard (может занять длительное время)
repadmin /replsummary [DCname|wildcard]
Проверьте USN записи:
repadmin /showutdvec
Если нужно принудительно синхронизировать конкретный контроллер домена с другими участниками репликации, выполните команду:
replmon /syncall msk-dc01
Далее обязательно проверьте синхронизацию времени на контроллерах домена командой:
w32tm /monitor
NTP offset должен быть около 0 для всех DC. Если нет, вам нужно схему проверить синхронизацию времени в вашем домене Active Directory.
Проверьте, что на всех контроллерах домена есть расшаренные сетевые папки SYSVOL и Netlogon. Эти папки нужны для применения и репликации групповых политик (объектов GPO).
Список общих папок на DC можно вывести командой:
net share
Теперь проверьте корректность работы Netlogons в Active Directory:
dcdiag /test:netlogons
Если с Netlogon все в порядке для всех тестов должно быть указано passed test.
Осталось проверить на любом компьютере домена, что к нему применятся все назначенные политики. Для этого используется команда:
gpresult
Администрирование инфраструктуры Active Directory — это непростой процесс. От правильного взаимодействия серверов зависит работа всей корпоративной сети, даже если у вас всего парочка контроллеров домена и один локальный сайт.
Утилита dcdiag позволяет выполнять различные тесты над инфраструктурой Active Directory и запрашивать диагностическую информацию о контроллерах домена.
Синтаксис dcdiag
Общий синтаксис
dcdiag [/s:<DomainController>] [/n:<NamingContext>] [/u:<Domain><UserName> /p:{* | <Password> | ""}] [{/a | /e}] [{/q | /v}] [/i] [/f:<LogFile>] [/c [/skip:<Test>]] [/test:<Test>] [/fix] [{/h | /?}] [/ReplSource:<SourceDomainController>]
Параметры dcdiag:
- /s:<DomainController>
Указывает контроллер домена. Если не указано, то используется локальный контроллер домена. Не используется в тестах DcPromo и RegisterInDns, которые можно выполнить только локально. - /n:<NamingContext>
Контекст именования в форматах NetBIOS, DNS (FQDN), DN. - /u:<Domain><UserName> /p:{* | <Password> | «»}
Запускает dcdiag от имени другого пользователя. По умолчанию dcdiag выполняется от имени текущего пользователя. - /a
Тестировать все серверы указанного сайта. - /e
Тестировать все серверы леса, перекрывает /a. - /q
Тихий режим. Выводятся только ошибки. - /v
Подробный режим. Выводится дополнительная информация. - /i
Игнорировать некритичные ошибки. - /fix
Только для теста MachineAccount. Исправление некорректных Service Principal Names (SPNs) на контроллере домена. - /f:<LogFile>
Вывод результатов в лог. - /c
Выполняет все тесты, кроме DCPromo и RegisterInDNS. Включает тесты не по умолчанию: Topology, CutoffServers, OutboundSecureChannels. Можно использовать совместно со /skip для пропуска определённых тестов. - {/h | /?}
Помощь. - /test:<Test>
Выполнить указанный тест. Дополнительно выполняется тест Connectivity. - /ReplSource:<SourceDomainController>
Только для теста CheckSecurityError. Проверяет соединение между контроллером домена, на котором выполняется команда, и исходным контроллером домена. SourceDomainController — это NetBIOS, DNS (FQDN) или DN имя сервера, который будет исходным контроллером домена для репликации.
Синтаксис для теста DNS
dcdiag /test:DNS [/DnsBasic | /DnsForwarders | /DnsDelegation | /DnsDynamicUpdate | /DnsRecordRegistration | /DnsResolveExtName [/DnsInternetName:<InternetName>] | /DnsAll] [/f:<LogFile>] [/x:<XMLLog.xml>] [/xsl:<XSLFile.xsl> or <XSLTFile.xslt>] [/s:<DomainController>] [/e] [/v]
Параметры dcdiag для теста DNS:
- /test:DNS
Тест DNS. По умолчанию /DnsAll. - /DnsBasic
Основные тесты DNS, соединение, конфигурация DNS клиента, доступность службы, существование зоны. - /DnsForwarders
Тесты DnsBasic и DNS-форвардинг. - /DnsDelegation
Тесты DnsBasic и проверка делегирования. - /DnsDynamicUpdate
Тесты DnsBasic и пределяет, включено ли динамическое обновление в зоне Active Directory. - /DnsRecordRegistration
Тесты DnsBasic tests и также проверяет, зарегистрированы ли записи A, CNAME и службы SRV. Кроме того, создается отчет об инвентаризации на основе результатов тестирования. - /DnsResolveExtName **[/DnsInternetName:<**InternetName>]
Тесты DnsBasic и делает resolve InternetName. Если DnsInternetName не указано, делает resolve www.microsoft.com. Если DnsInternetName указано, делает resolve указанного InternetName. - /DnsAll
Все тесты кроме DnsResolveExtName и создает отчет. - **/f:<**LogFile>
Вывод результатов в лог. - **/s:<**DomainController>
Указывает контроллер домена. Если не указано, то используется локальный контроллер домена. - /e
Все тесты DNS для всех контроллеров домена леса. - /v
Подробный режим. Выводится дополнительная информация. - /x:<XMLLog.xml>
Вывод результатов в <XMLLog.xml>. Только вместе с опцией /test:dns. - /xsl:<XSLFile.xsl> или <XSLTFile.xslt>
Добавляем файл стилей. Только вместе с опцией /test:dns /x:<XMLLog.xml>.
Тесты dcdiag
Тесты, которые нельзя пропустить
- Connectivity
Проверяет регистрацию DNS, ping, LDAP RPC для каждого контроллера домена.
Тесты, которые можно пропустить
- Replications
Проверяет возможность репликации между контроллерами домена и сообщает об ошибках репликации. - NCSecDesc
Проверяет, что дескрипторы безопасности в головках контекста именования имеют соответствующие разрешения для репликации. - NetLogons
Проверяет наличие соответствующих привилегий входа в систему для репликации. - Advertising
Проверяет, правильно ли контроллер домена сообщает о себе и о своих ролях, которые он должен выполнять. Этот тест завершиться неудачно, если служба NetLogon не запущена. - KnowsOfRoleHolders
Проверяет доступность контроллеров домена с ролями FSMO. - Intersite
Проверяет наличие ошибок, которые могут помешать нормальной репликации между сайтами. Результаты могут быть неточными. - FSMOCheck
Проверяет, что контроллер домена может подключиться к KDC, NTP, предпочтительному NTP, PDC, серверу глобального каталога. - RidManager
Проверяет RID мастера. - MachineAccount
Проверяет службы и регистрацию учетной записи целевого компьютера. Если обнаружена ошибка, ее можно исправить, указав параметры /FixMachineAccount или /RecreateMachineAccount. - Services
Проверяет службы контроллера домена. - OutboundSecureChannels
Проверяет наличие безопасных каналов между всеми контроллерами домена. - ObjectsReplicated
Проверяет правильность репликации Machine Account и Directory System Agent (DSA). Можно использовать **/objectdn:**dn и **/n:**nc параметры. - frssysvol
Проверяет FRS и SYSVOL. - frsevent
Проверка ошибок системы репликации. - kccevent
Проверка KCC. - systemlog
Проверка лога на наличие ошибок. - CheckSDRefDom
Проверяет, что все разделы каталога приложений имеют соответствующие домены ссылок на дескрипторы безопасности. - VerifyReplicas
Проверяет разделы каталога приложения на всех серверах, принимающих участие в репликации. - CrossRefValidation
Проверяет правильность перекрестных ссылок для доменов. - VerifyReferences
Проверяет, что системные ссылки не повреждены для FRS и репликации. - VerifyEnterpriseReferences
Проверяет, что системные ссылки не повреждены для FRS и репликации во всех объектах на каждом контроллере домена. - /skip:<Test>
Пропускает указанный тест. Connectivity выполняется всегда.
Тесты, которые не выполняются по умолчанию
- Topology
Проверяет, что KCC генерирует правильную топологию для всех контроллеров домена. - CheckSecurityError
Отчет об общем состоянии репликации в отношении безопасности Active Directory на контроллерах домена под управлением Windows Server 2003 SP1. Вы можете выполнить этот тест для одного или всех контроллеров домена на предприятии. По завершении теста dcdiag представляет сводку результатов, а также подробную информацию по каждому протестированному контроллеру домена и диагностику ошибок безопасности, о которых сообщил тест.
Cледующий аргумент является необязательным:
**/ReplSource:**SourceDomainController
Этот аргумент проверяет возможность создания связи репликации между реальным или потенциальным контроллером домена-источника (SourceDomainController) и локальным контроллером домена. - CutoffServers
Проверяет есть ли серверы репликации без партнёра. - DNS
Включает шесть дополнительных тестов. Имеет отдельный синтаксис, См. выше.
Тесты не для контроллеров домена
- DcPromo
Проверяет инфраструктуру DNS для любого компьютера, который вы хотите сделать контроллером домена. Если инфраструктура достаточна, вы можете сделать компьютер контроллером домена, указанном в параметре **/DnsDomain:**Active_Directory_Domain_DNS_Name. Этот параметр сообщает, требуются ли какие-либо изменения в существующей инфраструктуре DNS. Обязательным аргументом является **/DnsDomain:**Active_Directory_Domain_DNS_Name. Требуется один из следующих аргументов: /NewForest, /NewTree, /ChildDomain, /ReplicaDC. Если указан аргумент /NewTree, необходимо также указать аргумент **/ForestRoot:**Forest_Root_Domain_DNS_Name. - RegisterInDNS
Проверяет, может ли этот контроллер домена зарегистрировать Domain Controller Locator DNS записи. Эти записи должны присутствовать в DNS для других компьютеров, чтобы найти этот контроллер домена для домена Active_Directory_Domain_DNS_Name. Этот параметр сообщает, требуются ли какие-либо изменения в существующей инфраструктуре DNS. Обязательным аргументом является **/DnsDomain:**Active_Directory_Domain_DNS_Name.
Пример
Давайте продиагностируем какой-нибудь контроллер домена.
Запускаю прямо на контроллере домена выполнение всех тестов по умолчанию:
Проверим корректность работа DNS:
dcdiag /s:ilab-dc /test:dns /e
Все тесты пройдены успешно.
Ссылки
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc731968(v=ws.11)
This document is to serve basic step-by-step method to initiate the first and primary action of the overall troubleshooting process when a domain
controller is down.
Table of Contents
- 1. Check recent changes
- 2. Is everything on the domain controller working as intended?
- 3. Were networking devices altered in any way?
- References
1. Check recent changes
This can include patch management, services stopping unexpectedly, etc.
The approach you take is to look in the event logs in event viewer, system, application, security, and group policy logs are most common logs however a domain controller also has
Active Directory,
DNS, file services, AD web services logs as well as others that all can help point to the issue. Also, review the services.msc, make sure all
required services are started, stopped or services getting crashed. Make sure your domain controllers NIC information is correctly
stated. If running IPSEC verify your policy and make sure on both ends of the policy that it is correct and valid.
2. Is everything on the domain controller working as intended?
To verify this you open an admin command prompt and run the following commands:
- NET SHARE (This command will show if the sysvol is shared out or not)
- IPCONFIG / FlushDNS (DNS caching may generate a false impression that DNS «round robin» is not taking place from the DNS server to the Windows client)
- REPADMIN /KCC (KCC is Knowledge Consistency Check and this will recalculate the replication topology of your active directory infrastructure)
- REPADMIN /SYNCALL (This will force replicate with its replication partners)
- REPADMIN /SYNCALL APED
(This will force replicate to all domain controllers) - GPUPDATE /FORCE (This will enforce the group policy assigned to the domain controller)
- DCDIAG /C /V >C:dcdiag.txt
(This will perform a verbose mode DCDIAG and save it
to a text file) - Portqry.exe (This command-line utility is used to verify recommended AD port communication)
- w32tm /query /status (Verify Time Synchronization)
Needless to say that if any of these commands and outputs show any errors then you need to mark down the error and research from there.
3. Were networking devices altered in any way?
This involves routers, switches, firewalls, etc. Too often a network engineer makes changes that can break an Active Directory infrastructure and the best way to troubleshoot this is the following:
- Can you ping the device?
- Can you resolve DNS queries using
NSLOOKUP? (Using nslookup -a ipaddress) - Using LDP.EXE can you bind to the Active Directory store?
- Use a port query tool verify the required AD ports are open/ listening and not closed/ filtered?
- Talk with the network engineer. Ask if he or she changed the VLAN or
ACL’s that your AD infrastructure uses?
- Did he or she change/ update the intrusion prevention system?
- Did the switch port security kick in?
References
The links below are troubleshooting references.
- Service overview and network port requirements for Windows:
http://support.microsoft.com/kb/832017 - Troubleshooting Active Directory Replication Problems:
http://technet.microsoft.com/en-us/library/4f504103-1a16-41e1-853a-c68b77bf3f7e - Troubleshooting Active Directory Domain Services:
http://technet.microsoft.com/en-us/library/cc990288(v=ws.10).aspx - Diagnosing and Troubleshooting Active Directory Problems:
http://technet.microsoft.com/en-us/library/cc961826.aspx - Troubleshooting Active Directory-Related DNS Problems:
http://technet.microsoft.com/en-us/library/bb727055.aspx - Troubleshooting DNS:
http://technet.microsoft.com/en-us/library/cc753041.aspx
As stated in the beginning, this is a very basic approach to troubleshooting. Every infrastructure is different and as such the approach must be different, however, this guide is a baseline to the most basic of troubleshooting and can greatly help even the
most seasoned administrator quickly and proficiently find the exact problem and get a solution implemented.
Active Directory is a rather complex IT environment (even if when AD consists of primary domain controllers and one Active Directory site only). It is very important for a sysadmin to have the ability to check Active Directory health quickly and fix the problems. In this article, we’ll take a look at common commands that you can use to check the status of AD, find and fix possible errors.
DCDiag is an important utility to check domain controller health. Log in to any domain controller, open a command prompt as an administrator and run the command:
dcdiag /e /v /q
This command performs a general health test on domain controllers and Active Directory. This report will only list errors that require the attention of a domain administrator.
Then you need to check the health of the DNS servers (we run these commands in the PowerShell console):
DCDiag /Test:DNS /e /v /s:dc01.test.com >c:psDcdiagDNStest.txt
Then open the resulting report:
get-content c:psDcdiagDNStest.txt
If there is no problem with the DNS service, PASS should be indicated everywhere in the “Summary of DNS test results” section.
If there are errors in the report, try to fix them manually. If you cannot manually fix DNS errors, try fixing them using the dcdiag command with the fix parameter:
DCDiag /Test:DNS /e /v /s:dc01.test.com /fix
Then on all domain controllers run the command:
ipconfig /registerdns
After checking DCs and DNS, you need to check the health of Active Directory replication. Log in to any DC and check replication with the command:
repadmin /replsum
If the largest delta for any DC is less than 1 hour and replication fails = 0, then there are no replication problems in your domain.
Tip. The dcdiag and repadmin utilities are available on any DC with the ADDS role. If you want to use these tools on desktop Windows 10, you need to install RSAT.
If you found replication errors, you can get detailed information about them with the command:
repadmin /showreps
This command will show which naming context is not being replicated in AD.
The following command is used to quickly check replication on a specific DC. If you need to check replication on all DCs, use the wildcard parameter (may take a long time):
repadmin /replsummary [DCname|wildcard]
Check USN records:
repadmin /showutdvec
If you need to force synchronization of a specific domain controller with other replication participants, run the command:
replmon /syncall DC01
Next, be sure to check the time synchronization on the domain controllers with the command:
w32tm /monitor
NTP offset should be around 0 for all DCs. If not, check the time sync in the Active Directory domain.
Verify if all domain controllers have SYSVOL and Netlogon folders published as network shares. These folders are needed to apply and replicate Group Policy Objects. The list of shared folders on a DC can be displayed with the command:
net share
Now check if Netlogons is working correctly in Active Directory:
dcdiag /test:netlogons
If everything is fine with Netlogon, “passed test” should be specified for all tests.
It remains to check if all assigned policies are applied. You can do it on any computer in the domain using the gpresult command.
- About
- Latest Posts
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.
Keep an eye on Active Directory (AD) health with commands that are built into Windows Server.
@VPN_News UPDATED: July 25, 2022
Active Directory is coordinated by domain controllers. These controllers are essential to the smooth running of your AD implementations. Therefore, it is important to know how to check on their statuses.
A health check for Active Directory domain controllers can be performed with native Microsoft tools that cost nothing. However, there are some skills you need to acquire in order to carry out the check. We will show you how.
Repadmin
The first tool that you need in order to check up on your domain controllers is called repadmin. This is a command that is built into Windows Server, so you don’t need to download or install any software in order to use it.
All of the domains in a forest need to be coordinated through replication. The repadmin utility lets you check on how that process is faring by accessing a summary report from repadmin. This is available through the command repadmin /replsumary.
In the output of the summary, you will be able to see that all of your domain controllers are replicating properly. The largest replication delta means the longest time gap that occurred between replications for that domain controller. You can also see in the output if any replication activities failed.
You can get more detail of the replication activity of each domain controller with the command repadmin /showrepl. To limit the output to just the information for one domain controller, put its label at the end of the showrepl option, such as repadmin /showrepl DC1. The showrepl option will display the neighbors (replication partners) that update the domain controller.
You can home in on the replication errors if any were reported in the summary output by specifying the /errorsonly option, eg. repadmin /showrepl /errorsonly.
If one of your domain controllers is out of date, you can command an immediate replication run with the option repadmin /syncall. Name the domain controller that needs to be updated in the repadmin command. This command should be run on the server that hosts the AD domain. For example, to update domain controller DC2 immediately, you would use repadmin /syncall dc2. There is a long list of options that can be added to the end of this command. To see them all, enter repadmin /syncall /?.
To see the full list of repadmin commands, type repadmin /?.
Services-check in PowerShell
Access PowerShell to see that the Active Directory Domain services are running properly. These are the six services to look at:
- DNS server
- DFS replication
- Intersite messaging
- Kerberos key distribution
- Active Directory Domain Services
- NetLogon
In order to check that these four services are all running, use the following two lines:
$Services='DNS','DFS Replication','Intersite Messaging','Kerberos Key Distribution Center','NetLogon',’Active Directory Domain Services’
ForEach ($Service in $Services) {Get-Service $Service | Select-Object Name, Status}
Although this is a complicated request to write, the output is very straightforward, you should just get a report that each of these services is running.
DCDiag (dcdiag.exe)
A key tool that you need in order to keep tabs on your AD domain controllers is called DCDiag, or dcdiag.exe. This also covers issues around replication. As well as this, it can check on DNS servers and other essential services. The command is bundled in with the Remote Server Administration Tools (RAST) and it is also included with the AD DS role.
DCDiag is able to run 30 different tests on your Active Directory domain controllers and their supporting services. Among these tests are:
- Initial tests to verify the availability of key services and to ensure that they are contactable. These tests must be performed before all others and they can’t be left out. They check on the DNS server, that the domain controller can be contacted over the network, that the domain controller allows binding to an LDAP instance, and to the AD RPC interface.
- Advertising tests that check on the ability of other devices to locate the domain controller, which means that the controller is correctly notifying all other devices of its presence. The details of the response to this test are important – not just that there is a response – because it includes flags that indicate which services the domain controller can locate. These services are an LDAP server, the Write or Read-Only status, the time server, whether the DC is a global catalog and whether it is ready to respond, and the Key Distribution Center (KDC).
- Cross-reference objects test to see if the application partition’s cross-reference objects have the correct domain name.
- Cross-reference validation gets the naming contexts in the DC and checks them.
- Security services check to test that there is at least one reachable KDC per domain, that the Knowledge Consistency Checker (KCC) is working, that the GC’s computer object has replicated to other domain controllers, that it also has an account within the Active Directory setup that marks it as a domain controller and has the correct flags set. It also checks on the likelihood of fragmentation of Kerberos packets.
- DC connectivity tests examine whether all domain controllers can communicate with their partner DCs.
- File Replication Service tests look in the Event log for any error warnings related to the FRS that occurred over the last 24 hours. This is for Windows Server versions before 2008.
- Distributed File Service Replication tests examine DFSR Event log warnings over the last 24 hours to verify that the replication system is working correctly. This is for Windows Server 2008 and later.
- Registry key validation is carried out to ensure that the domain controller’s Netlogon SysvolReady value in the registry is properly set. This test contributes to the FRS and DFRS tests that are outlined above.
- Account validation makes sure that the user accounts that require access to the domain controller’s NetLogon and Sysvol values in order to function can actually get access. Other account-related tests include a verification that the account of the domain controller can access Active Directory and that it is marked as a Domain Controller account, that all flags on the account are correct and that it has the correct server reference. These account tests also offer repair options in the commands that run the checks.
- Object replication verification checks a small number of objects and attributes on several domain controllers to ensure that they have been replicated. The test will also show the last update date and time of each value on each instance. Note that this replication is for the data within the domain controller.
- Replication checks return data on recent replication attempts, showing statuses and times of each event. It particularly focuses on whether any replication took more than 12 hours and whether any domain controller has replication disabled.
- RID Master tests see whether the RID Master role holder can be located and contacted and has valid RID pool values.
- Services tests look at the statuses of all vital services for AD, such as DNS, FRS/DFRS, and KDC.
- Event log tests ensure that Windows Event logs related to Active Directory are being preserved. These print all related log messages from the last 60 minutes.
- Replication topology checks look at whether inter and intra-site replication is possible for a specific domain controller by exploring the settings of all upstream and downstream replication partners.
It is possible to see all of the test categories available in dcdiag.exe by issuing the command dcdiag /h.
How to run DCDiag tests
The dcdiag.exe program makes operating tests very easy. You don’t need to issue a command for each test. Instead, one short dcdiag.exe request launches a group of tests. Some guides tell you that you have to name the dcdiag program in full in order to run it, typing dcdiag.exe. However, this is not necessary – typing dcdiag is enough.
There are two formats to running the command depending on whether you want to query the domain controller that is resident on the host on which you run the command or on a DC that is hosted on a remote server. If you want to test a remote domain controller, you put its name immediately after the command with the /s: switch; if you are examining the local domain controller, you leave that bit out.
It is also possible to specify a username and password for a remote domain controller account. The label for the account name is /u: and for the password is /p. So, an example of a command to test a remote domain controller could be:
dcdiag /s:DC01 /u:Administrator /p:ComPlex1PssWd7
To run tests on a local domain controller, you would just need to type in
dcdiag
The good news is that this one command runs a battery of tests. There is a list of individual test names that you can run individually.
DCDiag options
DCDiag options go after the command and an optional identifier for a remote domain controller. You can get a list of them by entering dcdiag /? Or dcdiag /h. Here is the list:
- /a Test all domain controllers on this site.
- /e Test all domain controllers for this enterprise.
- /q Quiet mode. Only show error messages.
- /v Verbose mode. Display detailed information on each test.
- /c Comprehensive mode. Run all tests except DCPromo, RegisterInDNS, Topology, CutoffServers, and OutboundSecureChannels.
- /i Ignore superfluous error messages.
- /fix Fix the Service Principal Name (only for the MachineAccount test).
- /f: <filename> Send all output to the named file.
- /test: <testname> Perform only the named test.
- /skip: <testname> Skip the named test from the series.
- /ReplSource: <SourceDomainController> Test the relationship between the subject DC and the named DC.
It isn’t necessary to add any options to the command; DCDiag can be run alone, without any further keywords, just the command name itself.
Running specific tests with DCDiag (dcdiag.exe)
The straightforward dcdiag command runs a battery of tests. It is possible to just run one of these tests or a category of tests. For example, DNS-related tests are all grouped under the test name DNS. To run these tests on a local server, you just need to enter:
dcdiag /test:DNS
This command will run a suite of tests:
- DNSBasic Basic tests, such as connectivity, DNS client configuration, service availability, and zone existence.
- DnsForwarders Checks the configuration of forwarders plus the DnsBasic tests.
- DnsDelegation Checks for proper delegations plus the DnsBasic tests.
- DnsDynamicUpdate Checks whether a dynamic update is enabled in the Active Directory zone plus the DnsBasic tests.
- DnsRecordRegistration Checks if the address (A), canonical name (CNAME), and well-known service (SRV) resource records are registered, creating an inventory report. Also performs the DnsBasic tests.
- DnsResolveExtName [/DnsInternetName:<InternetName>] Tests the DNS records by resolving Microsoft.com. if the optional DnsInternetName is specified, this will be resolved instead. Also runs the DnsBasic tests.
- DnsAll Performs all tests, except for DnsResolveExtName.
As well as running a group of tests, the /test option can launch individual tests. So, in the DNS option above, the user could also choose to just run the DnsBasic package with the command:
dcdiag /test:DnsBasic
DCDiag (dcdiag.exe) is a very useful tool but be aware that some tests can take a long time to run. Especially if you use the /e option to test the entire system, don’t expect to see a report straight away. Those administrating the system for a large company with many inter-connected sites that share an AD structure should launch the command and then go to lunch while waiting for a response.
Summary
By using Repadmin, a PowerShell services check, and DCDiag, you can get a very good view of your AD structure. However, despite the great services of these free utilities, you will still be using manual methods to maintain a complicated IT system.
Active Directory is vital for effective system security but it can be difficult to visualize and manage. Consider an automated tool instead. You should check out ManageEngine ADManager Plus and the SolarWinds Active Directory Monitoring tool for some good automated AD management tools.
Domain Controller Health Check FAQs
How do I run a domain controller diagnostic?
For an Active Directory domain controller check, run the dcdiag command in a Command Prompt window with Administrator privileges. Typing the command by itself gives you a test on the local domain controller. You can also examine a remote domain controller by adding the option /s:<DC_name> where <DC_name is the domain controller that you want to test.
How can I tell if Active Directory is functioning properly?
Run dcdiag to check on the status of Active Directory. This tool provides 30 tests on domain controllers. You have to run it in a Command Prompt window that has been run as Administrator.
How do I check global catalog health?
Check on the status of the global catalog for Active Directory by opening a Command Prompt window as Administrator and running use dsquery server -isgc. Another option you should implement is to run the command dcdiag / v /c /d /e for a full status report.
Active Directory is a reliable, but complex and critical service, and the operability of the whole enterprise network depends on it. A system administrator should constantly check if Active Directory works correctly. In this article, we will go over the main methods of how to check and diagnose the health of your Active Directory domain, domain controllers, and replication.
Contents:
- How to Check AD Domain Controller Health Using Dcdiag?
- Checking Active Directory Replication Errors Between DCs
How to Check AD Domain Controller Health Using Dcdiag?
Dcdiag is a basic built-in tool to check Active Directory domain controller health. To quickly check the state of an AD domain controller, use the command below:
dcdiag /s:DC01
The command runs different tests against the specified domain controller and returns a state for each test (Passed/Failed).
Typical tests:
- Connectivity – checks if the DC is registered in DNS, establishes test LDAP and RPC connections;
- Advertising – checks roles and services published on the DC;
- FRSEvent – checks if there are any errors of file replication service (SYSVOL replication errors);
- FSMOCheck – checks if the DC can connect to KDC, PDC, and Global Catalog server;
- MachineAccount — checks if the DC account is registered in AD correctly and if the domain trust relationship is correct;
- NetLogons – checks the logon privileges to allow replication to proceed;
- Replications – checks the state of replication between domain controllers and if there are any errors;
- KnowsOfRoleHolders – checks the availability of the domain controllers with FSMO roles;
- Services – checks if services on the domain controllers are running;
- Systemlog – checks if there are any errors in the DC logs;
- Etc.
You can find a full description of all available dcdiag tests here.
Besides default tests, you can run additional domain controller checks:
- Topology – checks if KCC has generated full topology for all DCs
- CheckSecurityError
- CutoffServers – finds a DC that is not replicated since its partner is unavailable
- DNS – 6 DNS checks are available (
/DnsBasic
,/DnsForwarders
,/DnsDelegation
,/DnsDymanicUpdate
,/DnsRecordRegistration
,/DnsResolveExtName
) - OutboundSecureChannels
- VerifyReplicas – checks if the application partitions are replicated correctly
- VerifyEnterpriseReferences
For example, to check if DNS is working correctly on all domain controllers, use the following command:
dcdiag.exe /s:DC01 /test:dns /e /v
It will result in a summary table showing test results on how DNS resolves names on all DCs (if it is OK, you will see Pass in every cell). If you see Fail, you need to run this test against the specified DC:
dcdiag.exe /s:DC01 /test:dns /DnsForwarders /v
To get more information from domain controller test results and save it to a text file, use this command:
dcdiag /s:DC01 /v >> c:psdc01_dcdiag_test.log
The following PowerShell command displays only a summary information on the performed dcdiag tests:
Dcdiag /s:DC01 | select-string -pattern '. (.*) b(passed|failed)b test (.*)'
To get the state of all domain controllers, use:
dcdiag.exe /s:woshub.com /a
If you want to display only the errors you have found, use the /q option:
dcdiag.exe /s:dc01 /q
In my example, the tool has detected some replication errors:
There are warning or error events within the last 24 hours after the SYSVOL has been shared. Failing SYSVOL replication problems may cause Group Policy problems. ......................... DC01 failed test DFSREvent
To make dcdiag automatically fix the Service Principal Names errors for the DC account, use the /fix option:
dcdiag.exe /s:dc01 /fix
Checking Active Directory Replication Errors Between DCs
The built-in repadmin tool is used to check replication in the Active Directory domain.
Here is the basic command to check AD replication:
repadmin /replsum
The tool has returned the current replication status between all DCs. Ideally, the largest delta value should be less than 1 hour (depends on the AD topology and intersite replication frequency settings), and the number of errors = 0. In my example, you can see that one of the latest replication took 14 days, but now it is OK.
To check replication for all DCs in the domain:
repadmin /replsum *
To test intersite replication:
repadmin /showism
To view the replication topology and errors (if any), run this command:
repadmin /showrepl
The command will check the DCs and return the time and date of the last successful replication for each directory partition (last attempt xxxx was successful
).
To display additional replication info, use this command:
repadmin /showrepl *
To run password replication from a writable domain controller to a read-only domain controller (RODC), the /rodcpwdrepl option is used.
The /replicate option starts the replication of the specified directory partition to a specific DC immediately.
To synchronize a specified DC with all its replication partners, use the command below:
replmon /syncall <nameDC>
To view the replication queue:
repadmin /queue
Ideally, the replication queue should be empty.
Check when the latest backup of the current domain controller was created:
Repadmin /showbackup *
You can also check the replication state using PowerShell. For example, the following command will display all replication errors it finds in the Out-GridView table:
Get-ADReplicationPartnerMetadata -Target * -Partition * | Select-Object Server,Partition,Partner,ConsecutiveReplicationFailures,LastReplicationSuccess,LastRepicationResult | Out-GridView
You can also check the state of ADDS basic services on a domain controller using the Get-Service cmdlet:
- Active Directory Domain Services (
ntds
) - Active Directory Web Services (
adws
) – all cmdlets from the AD PowerShell module connect to this service - DNS (
dnscache
anddns
) - Kerberos Key Distribution Center (
kdc
) - Windows Time Service (
w32time
) - NetLogon (
netlogon
)
Get-Service -name ntds,adws,dns,dnscache,kdc,w32time,netlogon -ComputerName dc01
So, in this article, we have shown basic tools, commands, and PowerShell scripts you can use to diagnose the health of your Active Directory domain. You can use them in all supported Windows Server versions, including the domain controllers running in the Server Core mode.