Print IP Addresses and Hostnames From Host File on Windows

Print IP Addresses and Hostnames From Host File on Windows

The hosts file on a Windows system plays an important role in mapping IP addresses to hostnames, allowing for local domain resolution. Sometimes, it's useful to view the contents of this file to troubleshoot network issues or manage local DNS mappings. This tutorial demonstrates how to print IP addresses and hostnames from a host file on Windows.

Open the PowerShell window and run the following command to fetch the content of the hosts file and filter out empty lines and those starting with a # character, which are comments:

(Get-Content $env:SystemRoot\System32\drivers\etc\hosts) -notmatch '^(\s*$|#)'

Let's break down the command:

  • Get-Content - retrieves the content of the specified file.
  • -notmatch - operator to filter out lines that match the specified pattern.
  • ^(\s*$|#) - this regular expression is designed to match lines that are either empty, consist only whitespace characters (\s*), or start with a hash symbol (#). Its purpose is to effectively filter out lines containing comments and empty lines.

By using this command, we can easily print the IP addresses and hostnames from the hosts file. This can be especially helpful for managing local network configurations and troubleshooting DNS-related issues.

Output example:

127.0.0.1 app.local
127.0.0.1 test.local

Leave a Comment

Cancel reply

Your email address will not be published.