Dns-команды для windows, которые следует знать

In this article, we’ll reveal 10 PowerShell commands that you can use to manage your DNS server to keep everything under control as efficiently as possible.

In a previous article, we looked at how to deploy a DNS server using PowerShell commands, leaving you with a completely functional DNS server with very little effort.

Furthermore, we saw that by using scripts, you can replicate the process really easily for future deployments.

In this article, however, we’re going to see how you can use PowerShell commands to perform maintenance tasks. So, here are ten commands that you can use to manage your DNS server in the easiest way possible.

donfiealex

Revealing your Windows public IP address can be essential for various network-related tasks, and both PowerShell and Command Prompt (CMD) offer methods to quickly retrieve this information.

1. To reveal your public IP address using PowerShell, first open a PowerShell window. You can do this by searching for “PowerShell” in the Windows search bar and selecting the app.

2. Once the PowerShell window is open, you can use the Invoke-RestMethod cmdlet along with a public IP service to retrieve your IP address. For example, you can use a service like ‘ifconfig.io’ by running the command:

(Invoke-RestMethod -Uri ‘http://ifconfig.io/ip’).Trim()

3. Press Enter, and the public IP address associated with your network will be displayed in the PowerShell window.

Using Command Prompt (CMD):

1. To reveal your public IP address using Command Prompt, open a CMD window by searching for “Command Prompt” in the Windows search bar and clicking on it.

nslookup myip.opendns.com. resolver1.opendns.com

3. After running the command, CMD will display information about your public IP address, with the address itself listed under the “Address:” field.

By using these methods, you can easily Find Windows Public IP Address From PowerShell and CMD. Whether you need the information for setting up network configurations, accessing a remote server, or other networking tasks, having quick access to your public IP address can be highly useful. Always ensure that you are authorized to access and use any information related to public IP addresses in compliance with the relevant laws and regulations.








Dns-команды для windows, которые следует знать

At some point, most people with a computer have likely interacted with a command line interface. If you haven’t, here are the basics. With a program called a shell, you can execute tasks by entering a specific line of text known as a command. 

In this article, we’ll go through key Windows commands related to the Domain Name System (DNS). So, if you’ve ever wondered how to perform a Windows DNS lookup, this article is for you.

How to use commands on Windows

You have two options if you have a Windows machine and want to perform tasks using a command line interface: Windows Command Prompt (CMD) and Windows PowerShell. 

CMD

On Windows 10 or 11, you can easily find CMD by searching for “CMD” or “Command Prompt” in the search taskbar. You could also use the keyboard shortcut Win + R and search for it in the Run command window.

Windows PowerShell

Now that you know the basics of commands, let’s explore some important DNS commands on Windows.

Here are a few essential DNS commands and how to run them on CMD and PowerShell.

Nslookup

Nslookup is short for Nameserver lookup. If you’re having issues with DNS name resolution, this command can provide information such as the IP address of a host and more.

CMD

PowerShell

Nslookup is known as Resolve-DnsName in PowerShell:

DNS Record Lookup

You can use the DNS lookup command to check the DNS records for your domain. 

CMD

Powershell

Looking up DNS records in PowerShell requires the Resolve-DnsName cmdlet once more. Like with CMD, you must specify the record type by adding “-type record” at the end of the cmdlet. As an example:

Reverse DNS Lookup

With this command, you can find the name of a domain if you have the IP address.

CMD

Powershell

Ping Command

This command will help with performing network diagnostics and latency. 

:/>  Отключение акселерации мыши в Windows 10: способы выключить ускорение курсора

CMD

For this command, you’ll need the DNS address of the domain you want to test:

Powershell

With PowerShell, you just need the website name:

Traceroute Command

This command is also beneficial for network and connectivity troubleshooting. It traces a packet’s path from start to finish, showing all the hops it made along the way. 

CMD

You can use either the website name or IP address for the command:

Powershell

PowerShell – resolve-dnsname и nslookup выдают разные результаты

Сообщения: 6

Благодарности: 0


resolve-dnsname и nslookup выдают разные результаты при запросе одного хоста с одного dns сервера.

nslookup из cmd и ps выдает одинаковые (актуальные) результаты

Resolve-DnsName -Name $MyHost -Type A -Server $MyDNS -ErrorAction SilentlyContinue

выдает не актуальные результаты из некоего кеша (вчерашние)
На других машинах Resolve-DnsName выдает актуальный результат.

ipconfig /flushdns и Clear-DnsClientCache эффекта не оказали.

Как очистить кеш Resolve-DnsName?



Отправлено: 15:56,

23-08-2023

Сообщения: 6

Благодарности: 0


А так еще интереснее:
nslookup возвращает 1 запись
Resolve-DnsName другую
Resolve-DnsName -DnsOnly возвращает ошибку, не найдя имя (пробовал не только a записи искать)


Аватара для Pavel Nagaev

Сообщения: 136

Благодарности: 40


Чудес то не бывает, они что к разным DNS ходят?
Ставьте wireshark, трите кэши и смотрите к какому DNS идёт комп при nslookup и к какому при Resolve-DnsName

Я ваще не понимаю, как такое может быть.

Запускаете nslookup, видите IP адрес.
Запускаете Resolve-DnsName -Type A www.ru -Server и IP адрес сервера из nslookup

И что, получаете разные IP?

Попробуйте обе утилиты на какой-нибудь 8.8.8.8 натравить.

——-
Видео на русском про PowerShell
Крутые курсы по PowerShell


Сообщения: 6

Благодарности: 0


Pavel Nagaev, да разный. Поэтому и спросил у коллективного разума.

После ipconfig /flushdns и Clear-DnsClientCache.

Запрос одного имени, с одного сервера DNS (явно указанного по ip)

nslookup возвращает 1 запись
Resolve-DnsName другую
Resolve-DnsName -DnsOnly возвращает ошибку, не найдя имя (пробовал не только a записи искать)


Moderator


Resolve-DnsName -DnsOnly возвращает ошибку, не найдя имя

Покажите вывод с ошибкой.

nslookup -d имя_хоста


This was the result of a colloboration between me (with programming skills, but not in PowerShell!) and ChatGPT. It blows my mind away, what can be done with ChatGPT – this is what work IS supposed to be! Quick, without researching every single line. Human and machine in perfect colloboration:

# PowerShell script to get A and AAAA records for a list of domains, with debug output

# Define the path to the domain list and output CSV file
$domainListPath = "C:\your\path\domains.txt"
$outputCsvPath = ".\domain_records.csv"

# Read the list of domains from the file
$domains = Get-Content $domainListPath

# Prepare an array to hold the results
$results = @()

# Loop through each domain and query its A and AAAA records
foreach ($domain in $domains) {
    Write-Host "Processing domain: $domain"

    # Initialize the record object
    $record = New-Object PSObject -Property @{
        Domain = $domain
        ARecord = $null
        AAAARecord = $null
		WARecord = $null
		WAAAARecord = $null
    }

    Write-Host "  Performing nslookup..."
    # Perform nslookup for A and AAAA records
    $nslookupResults = nslookup $domain
	$nslookupResults = $nslookupResults | Select-Object -Skip 2

    # Extract A and AAAA records
    foreach ($line in $nslookupResults) {
		Write-Host "Debug output"
		Write-Host $line
        if ($line -match "(\d+\.\d+\.\d+\.\d+)") {
			$address = $matches[1]
			Write-Host "  Found A record: $address"
			$record.ARecord = $address
		} elseif ($line -match "([a-fA-F0-9:]+:[a-fA-F0-9:]+)") {
			$address = $matches[1]
			Write-Host "  Found AAAA record: $address"
			$record.AAAARecord = $address
		}
		
<#         if ($line -match "Address: (.*)") {
            $address = $matches[1]
            # Determine if the address is IPv4 (A record) or IPv6 (AAAA record)
            if ($address -match "\d+\.\d+\.\d+\.\d+") {
                Write-Host "  Found A record: $address"
                $record.ARecord = $address
            } elseif ($address -match "([a-fA-F0-9:]+:[a-fA-F0-9:]+)") {
                Write-Host "  Found AAAA record: $address"
                $record.AAAARecord = $address
            }
        } #>
    }
	
	Write-Host "  Performing www nslookup..."
    # Perform nslookup for A and AAAA records
    $nslookupResults = nslookup www.$domain
	$nslookupResults = $nslookupResults | Select-Object -Skip 2

    # Extract A and AAAA records
    foreach ($line in $nslookupResults) {
		Write-Host "Debug output"
		Write-Host $line
        if ($line -match "(\d+\.\d+\.\d+\.\d+)") {
			$address = $matches[1]
			Write-Host "  Found A record: $address"
			$record.WARecord = $address
		} elseif ($line -match "([a-fA-F0-9:]+:[a-fA-F0-9:]+)") {
			$address = $matches[1]
			Write-Host "  Found AAAA record: $address"
			$record.WAAAARecord = $address
		}
		
<#         if ($line -match "Address: (.*)") {
            $address = $matches[1]
            # Determine if the address is IPv4 (A record) or IPv6 (AAAA record)
            if ($address -match "\d+\.\d+\.\d+\.\d+") {
                Write-Host "  Found A record: $address"
                $record.ARecord = $address
            } elseif ($address -match "([a-fA-F0-9:]+:[a-fA-F0-9:]+)") {
                Write-Host "  Found AAAA record: $address"
                $record.AAAARecord = $address
            }
        } #>
    }

    # Add the record to the results array
    $results += $record
}

Write-Host "Exporting results to CSV..."
# Export the results to a CSV file
$results | Export-Csv -NoTypeInformation -Path $outputCsvPath

Write-Host "Script completed. Check $outputCsvPath for output."

# End of script

be sure to adjust the path in the line $domainListPath = “C:\your\path\domains.txt”.

The script can be saved as a .ps1 file, and then executed in the Windows PowerShell.

domains.txt looks like this, for example – simply one domain on each line:

7vi.de
7voice.de
airtaxi.to

The output looks like this:

Dns-команды для windows, которые следует знать

Summary

By knowing just a few PowerShell commands, you can make managing your DNS server much simpler and more efficient.

Thanks for choosing Jotelulu!

Did ChatGPT do this on it’s own?

No it did not – but it provided enough syntax and “how-to” for me, to be able to fix the problems quickly. In the comments you can see it’s original code, which took the NS server which I use.

This is an example of how to massively up your productivity and do new things, which you were not able to do before – because the time/output tradeoff would not allow you to.

This is an example of how to run checks and things you need, by spinning up your own scripts quickly.

(If I would have really wanted to do this in the old days, I would probably have used Ruby or Python, and written this on a Linux machine. My desktop happens to be – still – a Windows machine, so this is the convenient get it up quickly option here.)

PowerShell Commands for Managing Your DNS Server

Below, we’ve listed ten cmdlets that you can use to manage your DNS server quickly and easily. In reality, all the tasks listed here can be performed using the graphic interface, which might seem easier, but PowerShell is much quicker.

1. Stop the DNS Service

One of the most basic tasks that you need to know how to do is how to stop the service. This command can actually be used to stop all kinds of services but to stop the DNS service specifically, it will look something like this:

This command will only work on servers, not on client devices. On client devices, you can stop the cache but not the service entirely.

Command 1 - Stop the DNS service on the server using PowerShell
Command 1 – Stop the DNS service on the server using PowerShell

2. Start the DNS Service

Just as important as being able to stop the service is being able to start it again. And once again, this command can be used to start all kinds of services. But to start the DNS service, it will look like this:

Normally, you won’t see any confirmation message after running this command. Instead, if you want to check that the command has been run correctly, you can either launch the command “Get-Service DNS” or open the graphic interface.

Command 2 - Start the DNS service on the server using PowerShell
Command 2 – Start the DNS service on the server using PowerShell

3. Restart the DNS Service

You already know how to start and stop the service, but sometimes you might want to stop it and start again straight away.

Luckily, you can do this with a single reset command, which looks like this:

This command will order the server to re-read the configuration files, and that way, you can apply changes or resolve an error.

With these three commands, you’ve now got the basics taken care of.

Command 3 - Reset the DNS server using PowerShell
Command 3 – Reset the DNS server using PowerShell

4. Check DNS Resolution

Another common task is to check the name resolution to see whether the system can resolve a specific name.

The cmdlet “Resolve-DnsName” queries the DNS for the specified name.

There are two ways of using this command, as you can choose to specify the server to use if you wish.

If you don’t want to specify a server to use, the command will look something like this (using the Jotelulu website as an example):

Resolve-DnsName -Name www.jotelulu.com

However, if you want to use a specific server to resolve the query, the command will look like this:

Resolve-DnsName -Name www.jotelulu.com -Server 10.0.0.1

Command 4 - Check name resolution
Command 4 – Check name resolution

5. Show the DNS Cache

Now and again, you might be interested to see what the resolver cache looks like, whether from a server or a client device. To do this, you can either use the classic command prompt or use our good old friend PowerShell.

This command will return pages and pages of entries, so you might want to dump the results into a text document so you can examine it in more detail.

Command 5 - Show the contents of the DNS cache
Command 5 – Show the contents of the DNS cache

6. Clear the DNS Cache

This command can be run in between two queries so that you can see that the entries have been deleted.

Command 6 - Clear the DNS cache
Command 6 – Clear the DNS cache

7. Review the DNS Server Statistics

Another interesting thing you can do with PowerShell is consult the DNS Server statistics, which will show you things like entries, queries, etc.

You can perform this task using the graphic interface too, but PowerShell is still quicker. Here’s the cmdlet:

Again, there will be a lot of data here, so you’ll probably want to move it all into a text file for easier reading.

Command 7 - Review the DNS Server statistics
Command 7 – Review the DNS Server statistics

8. Review the DNS Service Settings

If you need to take a look at the settings for your DNS server, there’s a PowerShell command for that too!

A useful thing to do with the output of this command is to save it in a text file for future consultation. That way, you’ll have a record of previous settings if you make any changes later on.

Command 8 - Review your DNS Server settings
Command 8 – Review your DNS Server settings

9. Add New Service and Device Records

Another command task when managing a DNS server is registering all the services, devices and servers that your infrastructure uses.

To do this, you need to use the different kinds of records stored on the DNS server.

Add-DnsServerResourceRecordCName -ZoneName <ZONE_NAME> -Name  <ENTRY>  -HostNameAlias <FULL_ALIAS>

  • Add-DnsServerResourceRecordCName is the command to add a CNAME record.
  • ZoneName <ZONE_NAME> specifies the zone.
  • Name <ENTRY> specifies the name of the record.
  • HostNameAlias <FULL_ALIAS> specifies an alias for the new input

Here’s an example:

Add-DnsServerResourceRecordCName -ZoneName jotelulu.com -Name nacho-test -HostNameAlias nacho-test-jotelulu.com

This example adds a CNAME record. For other types of records, this command will vary.

Here are a few more examples.

For a PTR Record:

Add-DNSServerResourceRecordPTR -ZoneName 1.168.192.in-jotelulu.com -Name 12 -PTRDomainName nacho1-jotelulu.com

For an A Record:

Add-DnsServerResourceRecordA -Name pointer -IPv4Address 192.168.1.122 -ZoneName server1.jotelulu.com -TimeToLive 01:00:00

For an AAA Record:

Add-DnsServerResourceRecordAAAA -Name “nachopc” -ZoneName “jotelulu.com” -AllowUpdateAny -IPv6Address “fff4::1” -TimeToLive 01:00:00

For an MX Record:

Add-DnsServerResourceRecordMX -Preference 10  -Name “.” -TimeToLive 01:00:00 -MailExchange “mail.jotelulu.com” -ZoneName “jotelulu.com”

Command 9 - Add new service and device records to the DNS
Command 9 – Add new service and device records to the DNS

10. Remove Service and Device Records

Just as you can add records using PowerShell, you can also remove records from your DNS really easily using the command “Remove-DnsServerResourceRecord”. In fact, it’s almost exactly the same as the command to add a service. You just need to change the verb at the beginning.

Remove-DnsServerResourceRecord -ZoneName <ZONE_NAME> -RRType <RECORD_TYPE> -Name <ENTRY> –Force

  • Remove-DnsServerResourceRecord is the command to remove the record.
  • ZoneName <ZONE_NAME> specifies the zone.
  • RRType <RECORD_TYPE> specifies the type of record, such as A, AAA, MX, CNAME, etc.
  • Name <ENTRY> is the name of the record that needs to be removed.
  • Force: Forces the deletion.

As with the previous command, you need to distinguish between the different types of records (A, AAA, MX, etc.).

Here’s an example:

Remove-DnsServerResourceRecord -ZoneName jotelulu.com -RRType A -Name pc-jioller –Force

Command 10 - Remove records from the DNS
Command 10 – Remove records from the DNS

Оставьте комментарий