Monthly Archive


Reading the hosts file–revised

Quick revision to the post on reading the hosts file

I wanted to be able to display the whole file

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

so added an $all switch.  If this is selected the full contents of the file are displayed otherwise just the IP address entries are displayed as before

Leave a Reply