PowerShell for Windows Admins

Oct 23 2011   11:08AM GMT

Reading the hosts file

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Normally I ignore the Hosts file but my development laptop isn’t a member of my test domain – a number of reasons for this which I won’t go into.

This means that when I want to RDP to a machine in the test domain I have to use the IP address. A bit awkward but not too bad until I start changing the machines and I need to remember more IP addresses. Time to use the Hosts file then I can just refer to machine name.  First off need to be able to read the hosts file.

Could just use

Get-Content -Path C:\Windows\system32\drivers\etc\hosts

but that’s no fun.  Lets identify the bits of the file we need and junk the rest.

function get-hostfilecontent {            
 $file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"            
 if (-not (Test-Path -Path $file)){            
   Throw "Hosts file not found"            
 Get-Content -Path $file |             
 where {!$_.StartsWith("#")} |            
 foreach {            
  if ($_ -ne ""){            
  $data = $_ -split " ",2            
   New-Object -TypeName PSObject -Property @{            
     Server = $data[1].Trim()            
     IPAddress = $data[0].Trim()            

Create the path to the file and test it exists.  I’ve used the windir environmental variable just to be sure I can find it.

Run get-content on the file and filter out the comments (start with #). For each remaining record split it in 2 based on the first space. Only allow two substrings from the split in case multiple spaces were used. Take the resultant data and output as an object with 2 properties – server name and IPAddress.

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: