The dig
command is an essential DNS troubleshooting tool on Linux and macOS. However, attempting to use it in a Windows Command Prompt or PowerShell will return the errors as follows:
‘dig’ is not recognized as an internal or external command, operable program or batch file.
—
dig : The term ‘dig’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The Windows dig
equivalent are the Resolve-DnsName
command in PowerShell and the nslookup
command in Command Prompt.
Below is a quick guide on how to use these commands to check DNS records in Windows.
‘Dig’ vs ‘Resolve-DnsName’ vs ‘Nslookup’
‘A’ records show the IP address linked to a domain name. Use this to find out which server is hosting a website.
Resolve A records
Linux/macOS Shell:
$ dig shellhacks.com A
Windows PowerShell:
PS C:\> Resolve-DnsName -Name shellhacks.com -Type A
Windows Command Prompt:
C:\> nslookup -type=A shellhacks.com
Resolve MX records
‘MX’ records are for emails. They show which mail servers handle emails for a domain. This helps if there are email problems or you need to check the setup.
Linux/macOS Shell:
$ dig shellhacks.com MX
Windows PowerShell:
PS C:\> Resolve-DnsName -Name shellhacks.com -Type MX
Windows Command Prompt:
C:\> nslookup -type=MX shellhacks.com
Resolve all DNS records
If you want to check all the DNS details for a domain, resolving all DNS records is the way to go. This gives you a full picture, including different types like ‘A’, ‘MX’, and ‘AAAA’ records.
Linux/macOS Shell:
$ dig shellhacks.com any
Windows PowerShell:
PS C:\> Resolve-DnsName -Name shellhacks.com -Type any
Windows Command Prompt:
C:\> nslookup -type=any shellhacks.com
Conclusion
For users searching for a Windows dig equivalent, Resolve-DnsName
and nslookup
are the best alternatives. While Resolve-DnsName
offers more comprehensive details, nslookup
is simpler and more widely available. For more guidance on Windows alternatives, see our guides on the Windows “cat” command equivalent and Windows “grep” command equivalent.
Was it useful? Share this post with the world!
Обновлено:
Опубликовано:
Утилита и одноименная команда nslookup позволяет обращаться к серверу имен (NS) из командной строки. С ее помощью можно выполнить проверку работы DNS-сервера и созданных в нем записей. В данной инструкции подробно разберем работу с данной утилитой.
nslookup и синтаксис
Описание опций
Примеры
Аналоги
Ввод команды и синтаксис
Для работы с утилитой необходимо открыть командную строку (cmd или powershell в Windows и unix-shell в UNIX). В системах на базе Windows утилита встроена, и мы можем работать с ней в любой момент. Для некоторых дистрибутивов Linux потребуется установка утилиты одной из команд:
yum install bind-utils
apt install dnsutils
* первая команда для систем на базе Red Hat, вторая — Debian.
Для выполнения запросов используем команду:
nslookup [опции] <имя хоста для опроса или IP-адрес> [сервер DNS]
Самый простой пример использования команды:
nslookup dmosk.ru
… позволит получить IP-адрес для узла dmosk.ru.
Утилита также поддерживает работу в интерактивном режиме — вводим команду:
nslookup
После можно делать запросы.
Опции nslookup
При выполнении запросов мы можем использовать следующие опции:
Опция | Описание |
---|---|
Применяются для команды и интерактивного режима | |
all | Выводит параметры текущего запроса и настроек сервера DNS. |
class=X | Задает класс запроса, который указывает группу протоколов информации. Возможны варианты: 1. IN — Internet. Более, чем в 99% случаев используется он. 2. CHAOS, HESIOD — данные классы используются, крайне, редко. 3. ANY — запрос по всем возможным классам. |
d2 | Выводит полной информации по осуществлению запроса. |
nod2 | Обычный вывод (по умолчанию). |
debug | Покажет отладочную информацию по запросу. |
nodebug | Запрос без отображения отладочной информации (по умолчанию). |
defname | При запросе к хосту не FQDN автоматически подставит домен, который находится в настройках системы (DNS-суффикс). |
nodefname | Не подставлять домен. |
domain=’NAME’ | Задает домен, который должен быть подставлен к имени хоста (альтернатива DNS-суффиксу). |
querytype=TYPE | Указывает на тип запроса или тип записи, например, А, mx, txt и так далее. Аналогична опции type. |
recurse | Рекурсивный запрос (информация запрашивается у других серверов, если ее нет на используемом в запросе). |
norecurse | Запрет на использование рекурсивного запроса. |
retry=X | В случае долгого ответа, параметр позволяет указать количество повторов опроса. |
root | Назначает текущий DNS в качестве корневого сервера по умолчанию. |
root=NAME | Позволяет задать корневой сервер. |
search | Добавлять DNS-имена к имени хоста из списка доменов (сам список задается опцией srchlist). |
nosearch | Не использовать список доменов для подстановки к имени хоста. |
srchlist=N1[/N2/…/N6] | Задает список доменов, который нужно подставлять при использовании опции search. |
timeout=X | Задает время в секундах, сколько утилита должна ждать ответа от сервера. |
type=X | Указывает на тип записи, которую будем опрашивать. Например, для получения записи AAAA мы вводим опцию type=АААА. |
vc | Позволяет использовать виртуальную схему при отправке запросов. К сожалению, я не нашел подробного описания, что это значит. |
novc | Не использовать виртуальную схему при отправке запросов. |
Работают только в интерактивном режиме (задается без SET) | |
lsserver NAME | Задает имя сервера DNS. При определении имени NAME используется начальная настройка DNS. |
server NAME | Задает имя сервера DNS. При определении имени NAME используется текущее значение для DNS. |
Также мы можем вызвать описание для nslookup.
а) в системах на базе Windows:
nslookup
> help
б) в Linux:
man nslookup
Использование опций
При вводе команды nslookup к опциям добавляем дефис, например:
nslookup -timeout=1 -type=MX dmosk.ru
Если мы работаем с nslookup в интерактивном режиме, то опции задаются с помощью команды set:
> set debug
> dmosk.ru
* первая команда задает опцию для выполнения подробных запросов. Вторая — делает запрос для домена dmosk.ru.
Примеры использования
1. Запрос записи ipv6 для домена mail.ru.
а) команда:
nslookup -type=AAAA mail.ru
б) интерактивный режим:
> set type=AAAA
> mail.ru
2. Узнать NS серверы для домена google.com.
а) команда:
nslookup -type=NS google.com
б) интерактивный режим:
> set type=NS
> google.com
3. Определить mx-записи для yandex.ru через DNS-сервер 8.8.8.8
а) команда:
nslookup -type=MX yandex.ru 8.8.8.8
б) интерактивный режим:
> set type=MX
> server 8.8.8.8
> yandex.ru
* где мы указываем:
- type — тип записи, которую должны найти.
- server — сервер DNS, который будем опрашивать.
4. Запрос имени по IP-адресу (обратная зона)
а) команда:
nslookup -type=ptr 94.100.180.31
б) интерактивный режим:
> set type=ptr
> 94.100.180.31
Аналоги nslookup
1) В качестве альтернативы командной строке, можно воспользоваться различными онлайн сервисами для выполнения запросов к DNS. Например, на 2whois.ru.
2) Для Linux можно воспользоваться утилитой dig, которая также предназначена для выполнения запросов к DNS.
3) На мобильных устройствах, например, под управлением Android есть свои утилиты для опроса DNS. Например, Ping & Net.
Do you want to find the best NSLOOKUP alternatives for Windows? We have listed 10 Internet that are similar to NSLOOKUP. Pick one from this list to be your new NSLOOKUP app on your computers. These apps are ranked by their popularity, so you can use any of the top alternatives to NSLOOKUP on your computers.
Top 10 Software Like NSLOOKUP — Best Picks for 2025
The best free and paid NSLOOKUP alternatives for windows according to actual users and industry experts. Choose one from 10 similar apps like NSLOOKUP 2025.
Internet Explorer 10
IE10 brings to the table several handy features, such as fast browsing speed, improved protection against phishing, retrieved tabs from last session and moreWhen it comes to choosing the weapon of choice for browsing the Internet, the opinions are…
Developer: Microsoft
Internet Explorer 11 (Windows 7)
Microsoft’s last effort towards turning Internet Explorer into a competitive browser by offering the must-have for surfing the web along with some developer tools for tech-savvy usersGone are the days when Microsoft was trying to push its infamous browser,…
Developer: Microsoft
Internet Explorer 8
A web browser that provides support for a smart filter against malicious activity, accelerators that grant you speed, as well private mode for navigating on the Internet without leaving any tracesThe competition to gain the title of The Best…
Developer: Microsoft
Internet Explorer Administration Kit
Wizard-like application that enables you to create your own Internet Explorer 10 packages, by appending your files, customizing buttons and tweaking the many parameters providedInternet Explorer Administration Kit is a software program whose main purpose is to aid people…
Developer: Microsoft
Firefly Internet Phone
A fully-featured, free Internet phone with instant messaging and voicemail What’s new in Firefly Internet Phone 3.0.2 Build 4776: Brand new look and feel! Ability to have multiple calls in progress simultaneously New call handling including conference calls and…
Developer: Freshtel Pty Ltd
Internet Download Accelerator
An easy to use and efficient software solution that provides users with reliable acceleration, resuming, and management features for their downloads IMPORTANT NOTICE What’s new in Internet Download Accelerator 6.19.5.1651: Improved playlists download; Reduced disk space requirements for…
Developer: WestByte Software
Internet Download Manager (IDM)
Push your Internet connection to the limits and cleverly organize or synchronize download processes with this powerful applicationNOTE: After the installation process, in order to get the latest version (build) of IDM you can use the automatic update function…
Developer: Download Manager Tonec Inc
Becky! Internet Mail
Complex e-mail client that helps people check multiple accounts in the same time, schedule, filter and prioritize messages, manage contacts, set up notifications and customize the view What’s new in Becky! Internet Mail 2.75.01: BUGFIX: Failed to send mail…
Developer: RimArts Inc
Internet Download Manager (IDM)
Push your Internet connection to the limits and cleverly organize or synchronize download processes with this powerful applicationNOTE: After the installation process, in order to get the latest version (build) of IDM you can use the automatic update function…
Developer: Download Manager Tonec Inc
Complete Internet Repair
Repair Internet problems such as updates, configurations, hosts and cache files with the help of this simple and efficient application What’s new in Complete Internet Repair 5.2.3.4118: Optimized Functions. Cleaner Code. Resolute Compatibility. Read the full changelog Complete…
Developer: Rizonesoft
The fourth post in my PowerShell Beginner series, “Daily Tasks, The PowerShell Way“. Use PowerShell’s Resolve-DnsName cmdlet as a more powerful successor to ‘nslookup’.
What’s in a name?
Any seasoned IT Pro knows that the names we see for servers or in web URLs ultimately need to “resolve” or translate to a numerical IP address. Computers perform this resolution using a worldwide network of Domain Name System (DNS) servers. When your browser attempts to go to https://thinkpowershell.com, your computer will send a query to a DNS server with the hostname “thinkpowershell.com”, and the DNS server will return the IP address of the server hosting the website. Your DNS server will likely have to forward a query to other DNS servers to get the correct IP address.
nslookup (name server lookup) is a command line tool that has been around for years for performing this lookup activity on demand. You can specify the hostname or website domain name for which you want to “lookup” the IP address. Additionally, with the second positional parameter you can specify the IP address of a specific DNS server you want to query. It is a helpful tool, but it only returns CNAME , A, and AAAA record information, and not as a script-usable object.
C:\Users\aaron>nslookup www.microsoft.com 8.8.8.8 Server: google-public-dns-a.google.com Address: 8.8.8.8 Non-authoritative answer: Name: e10088.dspb.akamaiedge.net Addresses: 2600:1407:9:28c::2768 2600:1407:9:295::2768 23.72.44.137 Aliases: www.microsoft.com www.microsoft.com-c.edgekey.net www.microsoft.com-c.edgekey.net.globalredir.akadns.net
Use Resolve-DnsName for more control over DNS lookups
Using the Resolve-DnsName cmdlet, you can specify much more than just a hostname and DNS server. In its simplest form, you can run Resolve-DnsName hostname to perform a quick lookup against your computer’s configured DNS server.
PS C:\Users\aaron> Resolve-DnsName thinkpowershell.com Name Type TTL Section IPAddress ---- ---- --- ------- --------- thinkpowershell.com A 5284 Answer 173.236.158.197
You might be thinking,”that cmdlet name is more to type than nslookup”, but in reality it is 4 characters (“reso”) + TAB for it to autocomplete, so it is actually LESS typing.
The -Server parameter lets you specify the DNS server to which to send your query. Here we send it to Google DNS.
PS C:\Users\aaron> Resolve-DnsName thinkpowershell.com -Server 8.8.8.8 Name Type TTL Section IPAddress ---- ---- --- ------- --------- thinkpowershell.com A 5284 Answer 173.236.158.197
The Resolve-DnsName cmdlet has some additional parameters which make it more precise than nslookup. By default, your DNS Client service will try to resolve a hostname in the following order:
- Local HOSTS file
- DNS Client Resolver Cache
- DNS server query
If you are attempting to troubleshoot a hostname’s resolution, you may want more control over the name resolution logic than nslookup can give, because nslookup will immediately skip to step 3, query DNS server.
Local HOSTS File
For example, let’s say you have a HOSTS file entry for twitter.com to resolve to 10.10.10.10 and you want to make sure your computer is using the HOSTS file entry. If I run nslookup with the domain name, it queries my DNS server and returns the public IP for twitter.com:
C:\Users\aaron>nslookup twitter.com Server: shs1fw1 Address: 10.1.10.1 Non-authoritative answer: Name: twitter.com Addresses: 199.59.149.198 199.59.148.82 199.59.148.10 199.59.150.7
In contrast, if I run Resolve-DnsName with no additional parameters, it correctly returns the resolved address from the HOSTS file, even if I were to specify a DNS server with the -Server parameter.
PS C:\Users\aaron> Resolve-DnsName twitter.com Name Type TTL Section IPAddress ---- ---- --- ------- --------- twitter.com A 86400 Answer 10.10.10.10
Now let’s say I want to exclude HOSTS file resolution from my troubleshooting. I can use the -NoHostsFile parameter switch and it will skip step 1 in the resolution process.
PS C:\Users\aaron> Resolve-DnsName twitter.com -NoHostsFile Name Type TTL Section IPAddress ---- ---- --- ------- --------- twitter.com A 20 Answer 199.59.148.10 twitter.com A 20 Answer 199.59.150.7 twitter.com A 20 Answer 199.59.150.39 twitter.com A 20 Answer 199.59.149.230
DNS Client Resolver Cache and DNS Server query
Let’s take another example where you think your cached DNS entry for a server may be incorrect or non-existent. With Resolve-DnsName, you can use the –CacheOnly switch parameter to only resolve against step 1 and 2 (use it in conjunction with -NoHostsFile to only resolve against step 2). I’m using a website I haven’t attempted to go to in a long while. You can see that there is no entry currently in the cache, and I get an error.
PS C:\Users\aaron> Resolve-DnsName myspace.com -CacheOnly Resolve-DnsName : myspace.com : DNS record does not exist At line:1 char:1 + Resolve-DnsName myspace.com -CacheOnly + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (myspace.com:String) [Resolve-DnsName], Win32Exception + FullyQualifiedErrorId : RECORD_DOES_NOT_EXIST,Microsoft.DnsClient.Commands.ResolveDnsName
If I run Resolve-DnsName -DnsOnly, it will skip to step 3 and query the DNS server. I can then run it again with the -CacheOnly switch parameter and we see the entry is in the cache now.
PS C:\Users\aaron> Resolve-DnsName myspace.com -DnsOnly Name Type TTL Section IPAddress ---- ---- --- ------- --------- myspace.com A 4257 Answer 63.135.90.70 PS C:\Users\aaron> Resolve-DnsName myspace.com -CacheOnly Name Type TTL Section IPAddress ---- ---- --- ------- --------- myspace.com A 4232 Answer 63.135.90.70
Resolve different types of DNS records
Another big advantage of Resolve-DnsName is it can look up ANY type of DNS record, not just CNAME, A, or AAAA records. You use the -Type parameter with a value matching one of many common DNS record types.
For example, you want to see the Mail Exchange (MX) records for a domain:
PS C:\Users\aaron> Resolve-DnsName microsoft.com -Type MX Name Type TTL Section NameExchange Preference ---- ---- --- ------- ------------ ---------- microsoft.com MX 1843 Answer microsoft-com.mail.protection.outlook.com 10
Or perhaps you are trying to verify an SRV record (common for communication apps) for your Office 365 Skype for Business instance:
PS C:\Users\aaron> Resolve-DnsName _sipfederationtls.microsoft.com -Type SRV Name Type TTL Section NameTarget Priority Weight Port ---- ---- --- ------- ---------- -------- ------ ---- _sipfederationtls.microsoft.com SRV 3599 Answer sipfed.tip.lync.com 100 1 5061
Or finally, you want to validate a mail server that is sending mail to you on Microsoft’s behalf by looking up microsoft.com’s Sender Policy Framework (SPF) record, which is done with a TXT record:
PS C:\Users\aaron> Resolve-DnsName microsoft.com -Type TXT Name Type TTL Section Strings ---- ---- --- ------- ------- microsoft.com TXT 1284 Answer {v=spf1 include:_spf-a.microsoft.com include:_spf-b.microsoft.com include:_spf-c.microsoft.com include:_spf-ssg-a.microsoft.com include:spf-a.hotmail.com ip4:147.243.128.24 ip4:147.243.128.26 ip4:147.243.1.153 ip4:147.243.1.47 ip4:147.243.1.48 -all}
Return or pipe results as an object for other uses
The last major advantage Resolve-DnsName has over nslookup is the ease in which you can use the results of your queries. Resolve-DnsName returns a dynamic object based on the parameters used. This object’s properties can be accessed like any other PowerShell object. You can either pipe the output directly to another command (in this case Get-Member to show the TypeName and properties), or you can assign to a variable (shown below). Extremely useful for interactive sessions and scripting!
PS C:\Users\aaron> Resolve-DnsName _sipfederationtls.microsoft.com -Type SRV | Get-Member TypeName: Microsoft.DnsClient.Commands.DnsRecord_SRV Name MemberType Definition ---- ---------- ---------- QueryType AliasProperty QueryType = Type Target AliasProperty Target = NameTarget Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() CharacterSet Property Microsoft.DnsClient.Commands.DNSCharset CharacterSet {get;set;} DataLength Property uint16 DataLength {get;set;} Name Property string Name {get;set;} NameTarget Property string NameTarget {get;set;} Port Property uint16 Port {get;set;} Priority Property uint16 Priority {get;set;} Section Property Microsoft.DnsClient.Commands.DNSSection Section {get;set;} TTL Property uint32 TTL {get;set;} Type Property Microsoft.DnsClient.Commands.RecordType Type {get;set;} Weight Property uint16 Weight {get;set;} PS C:\Users\aaron> $result = Resolve-DnsName _sipfederationtls.microsoft.com -Type SRV PS C:\Users\aaron> $result.NameTarget sipfed.tip.lync.com
Next steps
Now that you are sold on using Resolve-DnsName over nslookup, here are some things to try:
- Run Clear-DnsClientCache and then run Resolve-DnsName hostname -CacheOnly, where hostname is any server or website of your choice. Verify there are no entries found in your cache.
- Run Resolve-DnsName hostname again. Then run Resolve-DnsName hostname -CacheOnly to confirm there is now an entry in the cache.
- Use the -Type parameter and some of the different DNS record types (see the TechNet article in the Reference section below for a full list) to examine the DNS records for your own organization’s domain. Check out things like the MX records and TXT records.
Reference
- technet.microsoft.com
- Resolve-DnsName
PS C:\Users\aaron> Get-Help Resolve-DnsName NAME Resolve-DnsName SYNOPSIS Performs a DNS name query resolution for the specified name. SYNTAX Resolve-DnsName [-Name] <String> [[-Type] <RecordType>] [-CacheOnly] [-DnsOnly] [-DnssecCd] [-DnssecOk] [-LlmnrFallback] [-LlmnrNetbiosOnly] [-LlmnrOnly] [-NetbiosFallback] [-NoHostsFile] [-NoIdn] [-NoRecursion] [-QuickTimeout] [-Server <String[]>] [-TcpOnly] [<CommonParameters>] DESCRIPTION The Resolve-DnsName cmdlet performs a DNS query for the specified name. This cmdlet is functionally similar to the nslookup tool which allows users to query for names. Note: The Resolve-DnsName cmdlet will return a maximum of 25 A and AAAA records from NS servers. RELATED LINKS Online Version: http://go.microsoft.com/fwlink/?linkid=287336 Nslookup on TechNet REMARKS To see the examples, type: "get-help Resolve-DnsName -examples". For more information, type: "get-help Resolve-DnsName -detailed". For technical information, type: "get-help Resolve-DnsName -full". For online help, type: "get-help Resolve-DnsName -online"
Резюме: Microsoft Scripting Guy, Ed Wilson продолжает разговор об использовании Windows PowerShell для диагностики DNS.
Microsoft Scripting Guy, Ed Wilson на связи. Вчера я рассказывал об использовании PowerShell для диагностики клиентских настроек DNS. В частности я говорил об определении текущего сервера DNS и клиентском DNS-кеше.
Сегодня мы рассмотрим еще пару функций.
Разрешаем DNS имена
Для того, чтобы выполнить подключение, мне нужно разрешить имя хоста в IP-адрес. Хотя, если быть точным, не мне, а моему компьютеру. Но если имя не будет разрешено должным образом, мое приложение не будет работать. Зачастую, во время путешествий короткий звонок в техподдержку превращается в долгий и мучительный звонок в техподдержку.
Поэтому я предпочитаю выполнить весь процесс траблшутинга самостоятельно, чтобы я мог сказать техподдержке, что им нужно сделать, чтобы решить моб проблему. Один из промежуточных шагов диагностики – это использование старой доброй утилиты NSLookup. Некоторое время назад я использовал специальную графическую утилиту NSLookup. Но это было довольно давно. Когда я начал заниматься консалтингом и мне пришлось работать с разными системами, я начал изучать использование NSLookup в командной строке, поскольку это была единственная утилита, в наличии которой я мог быть уверен. Однако использование NSLookup – это не самая веселая вещь.
«NSLookup» в PowerShell
К счастью мне не обязательно больше использовать NSLookup, поскольку Windows 8, Windows Server 2012 и даже Microsoft Surface обладают встроенным модулем DNSClient. Этот модуль содержит функцию Resolve-DNSName. Она работает просто замечательно (несмотря на тот факт, что сообщество полагает, что она должна называться Get-DNSName).
В наиболее простой форме использования, я просто указываю имя для разрешения в качестве аргумента Resolve-DNSName.
Resolve-DnsName www .scriptingguys.com
Команда и ее вывод приведены ниже.
14:28 C:\> Resolve-DnsName www .scriptingguys.com
Name Type TTL Section NameHost
—- —- — ——- ———
www. scriptingguys.com CNAME 3600 Answer scriptingguys.com
‘
Name : scriptingguys.com
QueryType : A
TTL : 3600
Section : Answer
IP4Address : 64.4.11.37
‘
Name : scriptingguys.com
QueryType : A
TTL : 3600
Section : Answer
IP4Address : 65.55.58.201
‘
Name : scriptingguys.com
QueryType : SOA
TTL : 3600
Section : Authority
NameAdministrator : msnhst.microsoft.com
SerialNumber : 2012050301
TimeToZoneRefresh : 1800
TimeToZoneFailureRetry : 900
TimeToExpiration : 2419200
DefaultTTL : 3600
Что здесь интересно, так это то, что выводятся три различных объекта. Они приведены ниже.
14:30 C:\> Resolve-DnsName www .scriptingguys.com | gm -MemberType Properties | select typename -Unique
TypeName
———
Microsoft.DnsClient.Commands.DnsRecord_PTR
Microsoft.DnsClient.Commands.DnsRecord_A
Microsoft.DnsClient.Commands.DnsRecord_SOA
Если мне нужна только запись определенного типа, я могу указать параметр –Type.
14:34 C:\> Resolve-DnsName www .scriptingguys.com -Type ptr
Name Type TTL Section NameHost
—- —- — ——- ———
www .scriptingguys.com CNAME 3251 Answer scriptingguys.com
Name : scriptingguys.com
QueryType : SOA
TTL : 3251
Section : Authority
NameAdministrator : msnhst.microsoft.com
SerialNumber : 2012050301
TimeToZoneRefresh : 1800
TimeToZoneFailureRetry : 900
TimeToExpiration : 2419200
DefaultTTL : 3600
К сожалению, параметр –Type не поддерживает указание нескольких значений. Сообщение об ошибке не выводится, однако это ведет к непредсказуемым результатам. Если мне нужно получить записи нескольких типов, я укажу эти типы в виде массива и передам их по конвейеру через командлет Foreach-Object.
«ptr», «a» | % {Resolve-DnsName -Name www .scriptingguys.com -Type $_}
Эту же технику я могу использовать для разрешения нескольких имен. Ниже я запрашиваю запись CNAME для имен «www.microsoft.com» and «ftp.microsoft.com».
«www.microsoft.com», «ftp.microsoft.com» | % {Resolve-DnsName $_ -type cname}
Если я хочу проверить DNS-кеш на наличие определенных записей, это я тоже могу сделать с помощью функции Resolve-DnsName. Если такой записи в кеше не существует (например она удалена по таймауту), выводится сообщение об ошибке.
14:41 C:\> Resolve-DnsName ftp.microsoft.com -CacheOnly
Resolve-DnsName : ftp.microsoft.com : DNS record does not exist
At line:1 char:1
+ Resolve-DnsName ftp.microsoft.com -CacheOnly
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (ftp.microsoft.com:String) [Resolve-DnsName], Win32Exception
+ FullyQualifiedErrorId : RECORD_DOES_NOT_EXIST,Microsoft.DnsClient.Commands.ResolveDnsName
Для проверки ответа, возвращаемого моим сервером DNS, я могу запросить его напрямую. Для этого существует несколько вариантов. Например, я могу указать, что хочу использовать только протокол DNS.
Resolve-DnsName ftp.microsoft.com –DnsOnly
С другой стороны, если проблема заключается в определенном DNS-сервере, я могу указать конкретный DNS-сервер для разрешения имени. Для начала мне нужно узнать, какие DNS-серверы используются моим компьютером. Для этого я воспользуюсь функцией Get-DNSClientServerAddress.
14:45 C:\> Get-DnsClientServerAddress
InterfaceAlias Interface Address ServerAddresses
————— ——— ——- —————
Local Area Connection* 14 33 IPv4 {}
Local Area Connection* 14 33 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
vEthernet (WirelessSwitch) 31 IPv4 {192.168.6.1, 64.134.255.2, 64.134…
vEthernet (WirelessSwitch) 31 IPv6 {}
isatap.owv.atl.wayport.net 44 IPv4 {192.168.6.1, 64.134.255.2, 64.134…
isatap.owv.atl.wayport.net 44 IPv6 {}
Local Area Connection* 12 25 IPv4 {}
Local Area Connection* 12 25 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
vEthernet (InternalSwitch) 19 IPv4 {192.168.3.100}
vEthernet (InternalSwitch) 19 IPv6 {}
isatap.{FC2087E9-6988-45E… 40 IPv4 {192.168.3.100}
isatap.{FC2087E9-6988-45E… 40 IPv6 {}
Loopback Pseudo-Interface 1 1 IPv4 {}
Loopback Pseudo-Interface 1 1 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
Teredo Tunneling Pseudo-I… 34 IPv4 {}
Teredo Tunneling Pseudo-I… 34 IPv6 {}
6TO4 Adapter 39 IPv4 {}
6TO4 Adapter 39 IPv6 {}
Для того, чтобы сделать вывод более удобочитаемым, я могу отфильтровать полученную информацию для вывода только тех записей, которые содержат адреса серверов.
14:46 C:\> Get-DnsClientServerAddress | ? serveraddresses
InterfaceAlias Interface Address ServerAddresses
————— ——— ——- —————
Local Area Connection* 14 33 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
vEthernet (WirelessSwitch) 31 IPv4 {192.168.6.1, 64.134.255.2, 64.134…
isatap.owv.atl.wayport.net 44 IPv4 {192.168.6.1, 64.134.255.2, 64.134…
Local Area Connection* 12 25 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
vEthernet (InternalSwitch) 19 IPv4 {192.168.3.100}
isatap.{FC2087E9-6988-45E… 40 IPv4 {192.168.3.100}
Loopback Pseudo-Interface 1 1 IPv6 {fec0:0:0:ffff::1, fec0:0:0:ffff::…
После получения списка DNS-серверов я могу начать их проверять по отдельности. Для этого я использую параметр -Server и укажу адрес определенного сервера.
Resolve-DnsName www .msn.com -DnsOnly -Server 192.168.6.1
Кроме того, я могу указать DNS-сервер по его имени.
Resolve-DnsName www .msn.com -Server ns1.msft.net
Если я понимаю, что в моем кеше содержатся неверные записи DNS, я могу его очистить.
Clear-DnsClientCache
Автор:
Ed Wilson, Microsoft Scripting Guy
Оригинал:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/08/replace-nslookup-with-a-built-in-windows-8-powershell-function.aspx
Страницы в социальных сетях:
Twitter: https://twitter.com/vsseth
Facebook: https://fb.com/inpowershell
VKontakte: https://vk.com/inpowershell