Reading the hosts file

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.

Leave a Reply