Dcdiag windows server 2019

Active Directory это надежный, но в то же время крайне сложный и критичный сервис, от работоспособности которого зависит работа всей вашей сети. Системный администратор должен постоянно мониторить корректность работы Active Directory. В этой статье мы рассмотрим основные методики, позволяющие вам быстро проверить и диагностировать состояние вашего домена Active Directory, контроллеров домена и репликации.

Содержание:

  • Проверка состояния контроллеров домена с помощью Dcdiag
  • Проверка ошибок репликации между контроллерами домена Active Directory

Проверка состояния контроллеров домена с помощью Dcdiag

Базовая встроенная утилита для проверки состояния контролеров домена – dcdiag.

Чтобы быстро проверить состояние конкретного контроллера домена AD воспользуйтесь командой:

dcdiag /s:DC01

Данная команда выполняет различные тесты указанного контроллера домена и возвращает статус по каждому тесту (Passed| Failed).

Типовые тесты:

  • Connectivity – проверяет регистрацию DC в DNS, выполняет тестовые LDAP и RPC подключения;
  • Advertising – проверяет роли и сервисы, опубликованные на DC;
    FRSEvent – проверяет наличие ошибок в службе репликации файлов (ошибки репликации SYSVOL);
  • FSMOCheck – проверяет, что DC может подключиться к KDC, PDC, серверу глобального каталога;
  • MachineAccount — проверяет корректность регистрации учетной записи DC в AD, корректность доверительных отношения с доменом;
  • NetLogons – проверка наличие прав на выполнение репликации;
  • Replications – проверка статуса репликации между контроллерами домена и наличие ошибок;
  • KnowsOfRoleHolders – проверяет доступность контроллеров домена с ролями FSMO;
  • Services – проверяет, запущены ли на контроллере домена необходимые службы;
  • Systemlog – проверяет наличие ошибок в журналах DC;
  • И т.д.

dcdiag проверка состояния контроллера домена active directory

Полное описание всех доступных тестов есть здесь.

Помимо стандартных тестов, которые выполняются по-умолчанию, можно выполнить дополнительные проверки контроллера домена:

  • Topology – проверяет, что KCC сгенерировал полную топологию для всех DC;
  • CheckSecurityError
  • CutoffServers – находит DC, который не получает репликацию из-за того, что партнёр недоступен;
  • DNS – доступны 6 проверок службы DNS (/DnsBasic, /DnsForwarders, /DnsDelegation, /DnsDymanicUpdate, /DnsRecordRegistration, /DnsResolveExtName)
  • OutboundSecureChannels
  • VerifyReplicas – проверяет корректность репликации разделов приложения
  • VerifyEnterpriseReferences

Например, чтобы проверить корректность работы DNS на всех контроллерах домена, используйте команду:

dcdiag.exe /s:DC01 /test:dns /e /v

dcdiag проверка службы DNS в домене

В результате должна появится сводная таблица по проверкам разрешения имен службой DNS на всех контроллерах (если все ОК, везде должно быть Pass). Если где-то будет указано Fail, нужно выполнить проверку этого теста на указанном DC:

dcdiag.exe /s:DC01 /test:dns /DnsForwarders /v

Чтобы получить расширенную информацию по результатам тестов контроллера домена и сохранить ее в текстовый файл, используйте команду:

dcdiag /s:DC01 /v >> c:\ps\dc01_dcdiag_test.log

расширенная диагностика состояния контроллера домена командой dcdiag

Следующая команда PowerShell позволяет вывести только информацию о выполненных тестах:

Dcdiag /s:DC01 | select-string -pattern '\. (.*) \b(passed|failed)\b test (.*)'

powershell скрипт - вывести информацию о тестах контроллера домена

Чтобы получить состояние всех контроллеров домена, используйте:

dcdiag.exe /s:winitpro.ru /a

Если нужно вывести только найденные ошибки, используйте параметр /q:

dcdiag.exe /s:dc01 /q

dcdiag вывести только ошибки

В моем примере утилита обнаружила ошибки репликации:

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

Чтобы утилита dcdiag попробовала автоматически исправить ошибки в Service Principal Names для данной учетной записи DC, используйте параметр /fix:

dcdiag.exe /s:dc01 /fix

Проверка ошибок репликации между контроллерами домена Active Directory

Для проверки репликации в домене используется встроенная утилита repadmin.

Базовая команда проверки репликации:

repadmin /replsum

repadmin /replsum проверка репликации в домене

Утилита вернула текущий статус репликации между всеми DC. В идеальном случае значение largest delta не должно превышать 1 час (зависит от топологии и настроек частоты межсайтовых репликаций), а количество ошибок = 0. В моем примере видно, что одна из последних репликаций заняла 14 дней, но сейчас все OK.

Чтобы выполнить проверку для всех DC в домене:

repadmin /replsum *

Проверку межсайтовой репликции можно выполнить так:

repadmin /showism

Для просмотра топологии репликации и найденных ошибках, выполните:

repadmin /showrepl

Данная команда проверит DC и вернет время последней успешной репликации для каждого раздела каталога (last attempt xxxx was successful).

repadmin /showrepl проверка последней успешной репликации между контроллерами домена

Для вывода расширенной информации, используйте:

repadmin /showrepl *

Для запуска репликации паролей с обычного контроллера домена на контроллер домена на чтение (RODC) используется ключ /rodcpwdrepl.

Опция /replicate позволяет запустить немедленную репликацию указанного раздела каталога на определенный DC.

Для запуска синхронизации указанного DC со всеми партнерами по репликации, используйте команду

replmon /syncall <nameDC>

Для просмотра очереди репликации:

repadmin /queue

В идеальном случае очередь должна быть пуста:

repadmin /queue - очередь репликации

Проверьте время создания последней резервной копии текущего контроллера домена:

Repadmin /showbackup *

Вы также можете проверить состояние репликации с помощью PowerShell. Например, следующая команда выведет все обнаруженные ошибки репликации в таблицу Out-GridView:

Get-ADReplicationPartnerMetadata -Target * -Partition * | Select-Object Server,Partition,Partner,ConsecutiveReplicationFailures,LastReplicationSuccess,LastRepicationResult | Out-GridView

проверка репликации с помощью Get-ADReplicationPartnerMetadata

Можете дополнительно с помощью Get-Service проверить состояние типовых служб на контроллере домена:

  • Active Directory Domain Services (ntds)
  • Active Directory Web Services (adws) – именно к этой службе подключаются все командлеты из модуля AD PowerShell
  • DNS (dnscache и dns)
  • Kerberos Key Distribution Center (kdc)
  • Windows Time Service (w32time)
  • NetLogon (netlogon)

Get-Service -name ntds,adws,dns,dnscache,kdc,w32time,netlogon -ComputerName dc03

проверка служб ADDS на контроллере домена

Итак, в этой статье мы рассмотрели базовые команды и скрипты, которые можно использовать для диагностики состояния вашего домена Active Directory. Вы можете использовать их во всех поддерживаемых версия Windows Server, в том числе на контроллерах домена в режиме Server Core.

Domain Controllers are the Most Crucial part of every AD Infrastructure and its best practice to ensure your running health checks and diagnostics on it regularly to ensure its health and functionality.

Today we’re going to take a deep dive into performing Domain Controller Health Checks & Best Practices.

The DCDiag tool is a Microsoft command-line utility that can be used to check the health of Active Directory domain controllers.

It is also used to diagnose DNS servers, AD replication, and other critical domain services within your Active Directory infrastructure.

These tests give you a brief overview of the overall health of your Active Directory Domain Controller.

This utility also allows you to check the health of all Domain Controller at a time.

With this utility, you can perform up to 30 different tests of your Active Directory Domain Controller to check its health status and other major issues that could be happening without you even knowing!

Some of the test performed by the DCDiag utility is shown below:

  • Connectivity
    Verify DNS registration for each domain controller and verify LDAP and RPC connections to each domain controller.
  • Advertising
    Checks whether the domain controller is correctly reporting or not.
  • CheckSDRefDom
    Checks that all application directory partitions have appropriate security descriptor reference domains.
  • CrossRefValidation
    Checks the validity of cross-references for domains.
  • FRSEvent
    Checks to see the errors in the file replication service.
  • FSMOCheck
    Checks the connectivity between the domain controller and KDC, PDC and a global catalog server.
  • MachineAccount
    Checks the registration status of the machine account.
  • NetLogons
    Checks the appropriate logon permissions to allow replication to proceed.
  • Replications
    Checks the replication status and errors between domain controllers.
  • RidManager
    Checks whether the RID manager is accessible or not.

In this guide, we will show you how to check the health of your Active Directory Domain Controller with DCDiag utility.

Install DCDiag

If you running the modern Windows Server 2019/2016/2012R2 versions and have AD DS and RSAT roles installed, then you already have Dcdiag installed.

In previous versions of Windows Server, you need to download and install the DCDiag utility from the following link:

https://www.microsoft.com/en-us/download/details.aspx?id=31063

In a Client OS versions Windows 10/8.1/7, you will need to install the RSAT tool and then install the DCDiag utility manually from the Support Tools package.

Basic Syntax of DCDiag

The basic syntax of the DCDial utility is shown below:

dcdiag.exe /s:Domain-Controller [OPTIONS]

A brief explanation of each option is shown below:

  • /s:Domain-Controller
    Used to perform tests against the remote Domain Controller.
  • /u:domain\username
    Allows you to specify the username of the remote Domain Controller.
  • /p:password
    Allows you to specify the password of the remote Domain Controller user.
  • /a
    Perform tests against all domain controllers.
  • /q
    Only display an error message after testing the domain controller.
  • /v
    Display detail information of each test.
  • /f
    Save the test result to a specified file.
  • /test:testname
    Used to perform only specific tests.
  • /skip:testname
    Used to skip the specific DCDiag test.

The DCDiag is a command-line tool. So you can run it on a Command Prompt or PowerShell window as an Administrative user.

You can display the help information about the DCDiag utility using the following command:

dcdiag.exe /h

You should see the following output:


Directory Server Diagnosis


cdiag.exe /s:[:] [/u:\ /p:*||""]
[/hqv] [/n:] [/f:] [/x:XMLLog.xml]
[/skip:] [/test:]
/h: Display this help screen


/s: Use as Home Server. Ignored for DcPromo and
RegisterInDns tests which can only be run locally.
/n: Use as the Naming Context to test
Domains may be specified in Netbios, DNS or DN form.
/u: Use domain\username credentials for binding.
Must also use the /p option
/p: Use as the password. Must also use the /u option
/a: Test all the servers in this site
/e: Test all the servers in the entire enterprise. Overrides /a
/q: Quiet - Only print error messages
/v: Verbose - Print extended information
/i: ignore - ignores superfluous error messages.
/c: Comprehensive, runs all tests, including non-default tests but excluding
DcPromo and RegisterInDNS. Can use with /skip
/fix: fix - Make safe repairs.
/f: Redirect all output to a file seperately
/x: Redirect xml output to . Currently works with /test:dns option only
/xsl: Adds the processing instructions that references specified stylesheet. Works with /test:dns /x: option only


/test: - Test only this test. Required tests will still
be run. Do not mix with /skip.
/skip: - Skip the named test. Required tests will still
be run. Do not mix with /test.

Run DCDiag on a Local Domain Controller

To perform the Domain Controller test on your local system, run the DCDiag utility without any argument:

dcdiag.exe

You should see the following screen:

dcdiag Domain Controller test on your local system

Run DCDiag on a Remote Server

If you want to check the health of a remote domain controller, run the DCDiag utility by specifying your remote domain controller name, administrator username and password as shown below:

dcdiag.exe /s:webserveradc.com /u:webserveradc.com\Administrator /p:password

You should see the tests result in the following screen:

check the health of a remote domain controller

Run DCDiag with Verbose Output

You can run the DCDiag utility with /v switch to display the results with more information.

dcdiag.exe /s:webserveradc.com /v

You should see the following screen:

DCDiag with Verbose Output

Run DCDiag and Save the Result to a File

If you want to save the test results in a file then you can use /f switch with DCDiag command as shown below:

dcdiag.exe /s:webserveradc.com f:c:\dcdiag.txt

This command will perform tests and save results in a file dcdiag.txt, or whatever you name it!

You can open this file as shown below:

DCDiag and Save the Result to a File

Run DCDiag to Test DNS

You can also test your DNS using the /test:dns switch as shown below:

dcdiag.exe /s:webserveradc.com /test:dns

You should see the results in the following screen:

DCDiag to Test DNS

Run DCDiag Against all Domain Controllers

If you have multiple domain controllers in your environment and want to perform tests against all domain controllers, then you can use /a switch with the DCDiag utility:

dcdiag.exe /s:webserveradc.com /a

Run DCDiag to Display Only Error Messages

If you want to remove the additional information from the test results and only want to display errors, you can use /q switch as shown below:

dcdiag.exe /s:webserveradc.com /q

If you found any errors after running the above command, you can fix it using the following command:

dcdiag.exe /s:webserveradc.com /fix

Run DCDiag to Perform Specific Test

The DCDiag utility also allows you to perform only specific tests by specifying its name.

For example, to perform only NetLogons test, you’ll run the following command:

dcdiag.exe /s:webserveradc.com /test:NetLogons

You should see the following screen:

DCDiag to Perform Specific Tests

You can also exclude a specific test from the checklist using the /skip switch.

For example, exclude the Replication test from the test results, run the following command:

dcdiag.exe /s:webserveradc.com /skip:Replication

You should see the following screen:

exclude a specific test from DCDIAG

Conclusion

Congratulations! you have successfully tested your Domain Controller with all available options using DCDiag utility.

We hope you have now enough understanding and knowledge of how to troubleshoot Domain Controller related issues with the DCDiag utility.

In this guide, we’ll go through a powerful MS Windows utility known as DCDiag. This tool can be used for performing domain controller health checks, testing DNS services, and even fixing errors automatically. The tool is very simple to use but powerful enough to keep all your domain controllers healthy.

Table of Contents

  1. What is the DCDiag utility? 
    • How to install DCDiag?
  2. What can you do with the DCDiag utility tool? 
  3. The DCDiag command syntax.
  4. How to run DCDiag?
    • Remote DC health checks.
    • Checking health for all DCs.
  5. Using DCDiag to test DNS.
  6. Customizing DCDiag results
    • Run DCDiag in quiet mode.
    • Run DCDiag with verbose output
    • Exporting DCDiag results.
  7. Additional Functions
    • Fix errors.
    • Specify or skip tests.
  8. Conclusion

1. What is the DCDiag Utility?

The DCDiag is a Microsoft Windows diagnostics command-line tool for domain controller health checks and troubleshooting. With the DCDiag, you can run about 30 different health checks on a domain controller and test DNS settings, replication health, errors, and more.

The DCDiag tool can be used to analyze a single or multiple DCs simultaneously within your AD forest or enterprise.

How to Install DCDiag?

It is very likely that if you are running Windows Server, you already have DCDiag installed.

The DCDiag is built into the modern Windows Server versions, including 2012R2, 2016, and 2019. For older versions, you would need to manually install it using the Support Tools package. The utility is available as long as you are running AD DS (Active Directory Domain Services), or AD LDS (Active Directory Lightweight Directory Services). If you want to run the DCDiag from a Windows OS client, you would need to install the RSAT roles on the computer.

2. What can you do with the DCDiag Utility tool?

As mentioned early, there are close to 30 different DCDiag checks. By default, the tool will perform about 22 checks, where 21 of those can be skipped, and the one remaining “connectivity check”, is forced.

The rest of the tests don’t run by default, so you would need to call for the specific test. The most popular among these tests is the DNS check.

Let’s review some of the different checks that DCDiag performs on a Domain Controller

  • Connectivity Check It tests whether the domain controllers are reachable, have LDAP/RPC connectivity, and are registered to DNS. This check can’t be skipped.
  • Advertising Verify if the Directory System Agent (DSA) is advertising itself.
  • CheckSecurityError This DCDiag test looks for security errors or any problem that might be related to security.
  • CutoffServrs It looks for servers that are not receiving replications.
  • DNS The DNS test checks the health of the DNS and its settings for the entire forest or enterprise.

  • Intersite Check for failures that would prevent an inter-site replication
  • Machine Account Checks the Machine Account to see if it has the proper information. The DCDiag has a “Fix” feature, which affects this test. You can make the test automatically fix SPNs on the MachineAccount object
  • ObjectsReplicated Checks whether the Machine Account and DSA objects have successfully replicated
  • RegisterInDNS Checks if the directory server can register the DS Locator DNS records
  • Topology Tests the connectivity of the topology for all DSAs

3. The DCDiag Command Syntax

The DCDiag is a simple command-line utility. You can run DCDiag on a CMD Prompt or a PowerShell window. Remember to use administrator privileges.

The basic syntax of DCDiag is:

  • dcdiag.exe /s:[:] [/u:\ /p:*||””]

Where “/s:” is Domain Controller, and “/u:\ /p” are username and password for the DC.

This basic command-line will return the test results showing the primary test (connectivity test) and any specified test on the domain controller.

To know what can you do with the DCDiag tool along with all its command-line switches, you can start with the help command:

  • C:\Windows\System32> dcdiag /?

To use any of the following switches, just append it after the “DCDiag” command. A summary of the popular command switches:

  • /s <DC name> Run DCDiag test against the specified remote Domain Controller.
  • /u <domain\username> use the credentials to connect to a remote DC.
  • /p <password> use along with /u to specify the password of the user.
  • /a Perform DCDiag tests against all DCs within a site.
  • /q (quiet) – Display only error messages.
  • /c (comprehensive) tests against the DC including DNS.
  • /v (verbose) – display extended information.
  • /f (filename) Save the results to the specified filename.

4. How to run DCDiag?

To run a simple DCDiag test on your local DC, type the DCDiag without any switch (or argument).

  • C:\Windows\System32>dcdiag.exe

Note, that DCDiag detects the current (local) DC, so you don’t have to specify any domain controller or administrative credentials. Of course, this is true as long as you are logged to the local domain controller and with administrator rights.

Remote DC Health Checks

To run diagnostics on a remote DC, you’ll have to specify the name of the DC by appending “/s:<name of DC>,” plus its credentials (username and password). For example:

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /u:dc01ny\Administrator /p:pa$$word

When you specify the DC “Directory Server” as in, (/s: <Directory Server>), there are some cases where the home DC specified with /s, will be ignored. The /s switch will ignore DCPromo and the Register in DNS, which are run locally and not for a domain controller.

Note that when you enter the /u (username) information, you’ll need to specify the name of the account with domain admin permissions and using the right format: domain/username. For example, the username (Administrator) appended with the domain name (dc01ny): u:dc01ny\Administrator.

Checking health for all DCs

Each AD’s site may contain a collection of DCs that are interconnected to each other. If your AD is divided into sites, then the “/a” switch is very helpful. It allows you to run the DCDiag utility for all DCs within a site, at once.

For example: 

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /a

5. Using DCDiag to test DNS

By default, and regardless of whatever you are testing, the DCDiag tool will always check the DNS registration for each domain controller, during the primary connectivity test. Additionally, you may also run very specific DNS tests, including forwarders, registration records tests, and more— all of which will help you troubleshoot DNS issues.

To test DNS and run various diagnostics, use the /test:dns switch. The command syntax is as follow:

  • dcdiag /test:DNS

An example? 

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /test:dns

By default, the /test:dns will perform all the following basic tests on DNS except, the external name resolution. The DNSBasic test is shown in all DNS results. If no test is specified, the /test:dns switch will default to /DNSall.

  1. /DNSBasic The basic DNS test includes network connectivity, DNS client, zones, and service availability.
  2. /DnsForwarders Performs the basic test and checks the configuration of DNS forwarders.
  3. /DnsDelegation Basic and DNS delegation test.
  4. /DnsDynamicUpdate Runs the basic test and checks whether dynamic DNS updates are enabled in AD.
  5. /DnsRecordRegistration Performs the /DNSBasic test and checks the registration of resource records (A, CNAME, and SRV).
  6. /DnsResolve<Internet Name> Performs the basic DNS tests and attempts to resolve the <Internet name>
  7. /DnsResolveExtName <internet name> To test DNS resolution for external names.
  8. /DNSAll Perform all above tests, except the /DnsResolveExtName.

A DNS test would look like this:

When you run the /test:dns you can also save all results of the output to a log file, using “/f:” for txt, “/x:” for XML, and “/xsl:” for XLS.

6. Customizing DCDiag Results

DCDiag allows you to customize the results by showing you less or more information. You can also export the results for later analysis.

Run DCDiag in quiet mode

The standard output of the DCDiag test is already quite extensive. Anyone skipping through it may easily miss an error message. This is why the “/q” switch becomes quite handy, as it reduces the size of the output by displaying only the error message list.

An example of DCDiag in quiet mode: 

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /q

The /q output is filtered only to errors. It looks like this:

Run DCDiag with Verbose Output

Run DCDiag with verbose output by appending the /v, verbose switch. With it, you’ll get additional details from the standard output, such as errors, warnings, informational messages, etc. The “/v” switch is the opposite of the “/q” switch. It extends the size of the output.

As mentioned earlier, the DCDiag (without /v) provides enough information to troubleshoot and diagnose any problem in your domain controller, which might be enough in most cases.

An example of the verbose switch: 

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /v

The verbose output looks like this.

The verbose output is recommended only if you see errors or warnings in the standard summary table and you want to investigate the problem with more details.

Exporting DCDiag Results.

The DCDiag utility tool allows you to export the health check results. All results of the test will be saved into a text file, by appending the “/f” switch to the DCDiag command.

For example:

  • C:\Windows\System32>dcdiag.exe /s:dc01ny f:c:\dcdiag_dc01ny_test01.txt

Note that you can customize the name of the log file and save it in any specific folder. You can open the results in notepad or any program that supports .txt files.

Export to XML and XLS? You can also export results to XML or XSL. but this function only works for the /test:dns switch:

For example:

  • /test:dns /x<XMLLog.xml> or, /test:dns/x:<XMLLog.xml>

7. Additional Functions

DCDiag also allows you to perform additional functions like fixing issues, which is outside normal diagnosis. You can also customize the running tests, by either specifying a single test or skipping any.

Fix Errors

The DCDiag is a purely diagnostic tool. It runs various tests and only reports back its results. But there is a fantastic switch that attempts to make safe repairs on the reported errors: the /fix switch.

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /fix

When you use the /fix switch, you don’t need to specify any additional parameters or attributes. The /f switch only works for the MachineAccount test. It fixes the Service Principal Names (SPNs) on the MachineAccount object of the DC.

A word of caution! Even though the (fix) switch is designed to make safe automatic repairs, it is still making changes to the domain controller. Before using the /f switch, analyze the test results and always perform a backup of the domain controller.

Perform Specific Tests or Skip them

As mentioned earlier, some DCDiag tests do not run by default, so they’ll need to be specified. The (/test:) switch allows you to perform only one test (plus the primary connectivity test). You can either call for one of those tests that don’t run by default or specify a default test if you want to shorten the output.

The syntax for this command is: 

  • /test:<TestName>

An example of this switch is when you use it with the DNS test:

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /test:dns

Or,

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /test:CheckSecurityError 

Additionally, you can make the DCDiag tool exclude specific tests. The (/skip:) switch is helpful when you want to get cleaner results in any manual or automated script test. Do not mix this parameter with the (/test). You can’t apply the skip switch to the Connectivity Test.

The syntax for this command is: 

  • /skip:<Test>

An example?

  • C:\Windows\System32>dcdiag.exe /s:dc01ny /skip:Replication

Conclusion

The DCDiag is an easy-to-use and simple, yet powerful utility for checking the health of your domain controllers. DCDiag can help you troubleshoot DNS issues, AD replication, and other domain service problems.

To expand your domain controllers’ health checks and monitoring efforts and keep track of other key services like DNS and DHCP, use the SolarWinds Server & Application Monitor (SAM). This tool helps you identify DC issues, extend the visibility of the DC’s performance, prevent replication failures, keep track of failed logins, manage DS files, and a lot more.

Another automated health check system option is ManageEngine ADManager Plus. This system provides a list of reports, which perform health checks on your AD Domain Controllers as they run. The tool also provides a single interface for your multiple AD instances, covering Exchange, SharePoint, and Office 365 as well as your general AD access controls. The service provides standard admin functions and includes a great deal of system maintenance automation.

Recently I have needed to collect information from domain controllers to generate a pre-migration report. To perform this task, I used different tools available on Windows Server. Today, in this post, I will show you how to collect information from domain controllers using a PowerShell script and command-line tools such as DCDIAG and NLTEST.

PowerShell Workaround>

PowerShell Workaround

#

Using the following script, we will obtain the requested information about all domain controllers that are online in our domain. Requirements:

  • PowerShell version 3.0 or higher.
  • PowerShell Active Directory module. To learn how to install this module, see this
    link.
# Import AD module
Import-Module ActiveDirectory

# Get your ad domain name
$DomainName = (Get-ADDomain).DNSRoot

# Get all Domain Controllers
$DCs = Get-ADDomainController `
    -Filter * `
    -Server $DomainName `
    | Select-Object Hostname,isGlobalCatalog,IsReadOnly,Site,Forest,OperationMasterRoles

# Create empty DataTable object
$DCTable = New-Object System.Data.DataTable


$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[0].Caption = "Hostname"
$DCTable.Columns[0].ColumnName = "Hostname"

$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[1].Caption = "isGlobalCatalog"
$DCTable.Columns[1].ColumnName = "isGlobalCatalog"
$DCTable.Columns[1].DataType = "Boolean"

$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[2].Caption = "IsReadOnly"
$DCTable.Columns[2].ColumnName = "IsReadOnly"
$DCTable.Columns[2].DataType = "Boolean"

$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[3].Caption = "Site"
$DCTable.Columns[3].ColumnName = "Site"

$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[4].Caption = "Forest"
$DCTable.Columns[4].ColumnName = "Forest"

$DCTable.Columns.Add() | Out-Null
$DCTable.Columns[5].Caption = "OperationMasterRoles"
$DCTable.Columns[5].ColumnName = "OperationMasterRoles"
$DCTable.Columns[5].DataType = "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"


ForEach($DC in $DCs)
{


    $DCTable.Rows.Add(  $DC.Hostname,
                        $DC.isGlobalCatalog,
                        $DC.IsReadOnly,
                        $DC.Site,
                        $DC.Forest,
                        $DC.OperationMasterRoles
                    )| Out-Null
}

# Display results in the console
$DCTable

The information collected is stored in a table and is shown at the end of the execution of the script as shown in the following screenshot.

Get-ADDomanController

If you want to know more about the Get-ADDomainController cmdlet, check out this link:
https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-addomaincontroller?view=winserver2012-ps

DCDIAG>

DCDIAG

#

The following command will display the list of services a domain controller is advertising.

dcdiag /v /s:<_DomainControllerName_> /test:advertising
Services DC

If you want to know more about dcdiag command-line tool, check out this link:
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc731968(v=ws.11)

NLTEST>

NLTEST

#

You can also use the nltest command-line tool. By running the following command on a domain controller, you will get the following result:

nltest /server:<_DomainControllerName_> /dsgetdc:<_DomainName_>
Services DC

Flags>

Flags

#

The data received from the request contains a set of indicators that describe the domain controller. This can be zero or a combination of one or more of the following values.

  • DS_DNS_CONTROLLER_FLAG: The DomainControllerName member is in DNS format.

  • DS_DNS_DOMAIN_FLAG: The DomainName member is in DNS format.

  • DS_DNS_FOREST_FLAG: The DnsForestName member is in DNS format.

  • DS_CLOSEST_FLAG: The domain controller is on the same site as the client.

  • DS_DS_FLAG: The domain controller is a directory service server for the domain.

  • DS_FULL_SECRET_DOMAIN_6_FLAG: The domain controller is a Windows 2008 or later writable domain controller.

  • DS_GOOD_TIMESERV_FLAG: The domain controller is running a reliable Windows Time Service for the domain.

  • DS_GC_FLAG: The domain controller is a global catalog server for the forest specified by DnsForestName.

  • DS_KDC_FLAG: The domain controller is a Kerberos Key Distribution Center for the domain.

  • DS_LDAP_FLAG: The server is an LDAP server.

  • DS_NDNC_FLAG: The Domain Name is an application (non-domain) naming context.

  • DS_PDC_FLAG: The domain controller is the primary domain controller of the domain.

  • DS_SELECT_SECRET_DOMAIN_6_FLAG: The domain controller is a Windows 2008 or later read-only domain controller.

  • DS_TIMESERV_FLAG: The domain controller is running the Windows Time Service for the domain.

  • DS_WRITABLE_FLAG: The domain controller hosts a writable directory service (or SAM).

Thanks for reading until the end. I hope you find this article useful and share it.

If you want to know more about nltest command-line tool, check out this
link
.

Администрирование инфраструктуры 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.

Пример

Давайте продиагностируем какой-нибудь контроллер домена.

Запускаю прямо на контроллере домена выполнение всех тестов по умолчанию:

  • dcdiag

    dcdiag
    
    Directory Server Diagnosis
    
    Performing initial setup:
       Trying to find home server...
       Home Server = ilab-dc
       * Identified AD Forest. 
       Done gathering initial info.
    
    Doing initial required tests
       
       Testing server: Default-First-Site-Name\ILAB-DC
          Starting test: Connectivity
             ......................... ILAB-DC passed test Connectivity
    
    Doing primary tests
       
       Testing server: Default-First-Site-Name\ILAB-DC
          Starting test: Advertising
             ......................... ILAB-DC passed test Advertising
          Starting test: FrsEvent
             ......................... ILAB-DC passed test FrsEvent
          Starting test: DFSREvent
             ......................... ILAB-DC passed test DFSREvent
          Starting test: SysVolCheck
             ......................... ILAB-DC passed test SysVolCheck
          Starting test: KccEvent
             ......................... ILAB-DC passed test KccEvent
          Starting test: KnowsOfRoleHolders
             ......................... ILAB-DC passed test KnowsOfRoleHolders
          Starting test: MachineAccount
             ......................... ILAB-DC passed test MachineAccount
          Starting test: NCSecDesc
             ......................... ILAB-DC passed test NCSecDesc
          Starting test: NetLogons
             ......................... ILAB-DC passed test NetLogons
          Starting test: ObjectsReplicated
             ......................... ILAB-DC passed test ObjectsReplicated
          Starting test: Replications
             ......................... ILAB-DC passed test Replications
          Starting test: RidManager
             ......................... ILAB-DC passed test RidManager
          Starting test: Services
             ......................... ILAB-DC passed test Services
          Starting test: SystemLog
             ......................... ILAB-DC passed test SystemLog
          Starting test: VerifyReferences
             ......................... ILAB-DC passed test VerifyReferences
       
       
       Running partition tests on : ForestDnsZones
          Starting test: CheckSDRefDom
             ......................... ForestDnsZones passed test CheckSDRefDom
          Starting test: CrossRefValidation
             ......................... ForestDnsZones passed test
             CrossRefValidation
       
       Running partition tests on : DomainDnsZones
          Starting test: CheckSDRefDom
             ......................... DomainDnsZones passed test CheckSDRefDom
          Starting test: CrossRefValidation
             ......................... DomainDnsZones passed test
             CrossRefValidation
       
       Running partition tests on : Schema
          Starting test: CheckSDRefDom
             ......................... Schema passed test CheckSDRefDom
          Starting test: CrossRefValidation
             ......................... Schema passed test CrossRefValidation
       
       Running partition tests on : Configuration
          Starting test: CheckSDRefDom
             ......................... Configuration passed test CheckSDRefDom
          Starting test: CrossRefValidation
             ......................... Configuration passed test CrossRefValidation
       
       Running partition tests on : ilab
          Starting test: CheckSDRefDom
             ......................... ilab passed test CheckSDRefDom
          Starting test: CrossRefValidation
             ......................... ilab passed test CrossRefValidation
       
       Running enterprise tests on : ilab.local
          Starting test: LocatorCheck
             ......................... ilab.local passed test LocatorCheck
          Starting test: Intersite
             ......................... ilab.local passed test Intersite
    

dcdiag

Проверим корректность работа DNS:

  • dcdiag /s:ilab-dc /test:dns /e

    dcdiag /s:ilab-dc /test:dns /e
    
    Directory Server Diagnosis
    
    Performing initial setup:
       * Identified AD Forest. 
       Done gathering initial info.
    
    Doing initial required tests
       
       Testing server: Default-First-Site-Name\ILAB-DC
          Starting test: Connectivity
             ......................... ILAB-DC passed test Connectivity
    
    Doing primary tests
       
       Testing server: Default-First-Site-Name\ILAB-DC
       
          Starting test: DNS
             
             DNS Tests are running and not hung. Please wait a few minutes...
             ......................... ILAB-DC passed test DNS
       
       Running partition tests on : ForestDnsZones
       
       Running partition tests on : DomainDnsZones
       
       Running partition tests on : Schema
       
       Running partition tests on : Configuration
       
       Running partition tests on : ilab
       
       Running enterprise tests on : ilab.local
          Starting test: DNS
             ......................... ilab.local passed test DNS
    
    

dcdiag

Все тесты пройдены успешно.

Ссылки

https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc731968(v=ws.11)

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Спектроанализатор звука программа на windows
  • Гаджеты для windows 10 прогноз погоды
  • Как перевернуть пуск вниз windows 10
  • Iphone manager for windows
  • Windows host process rundll32 не отвечает