Monthly Archive


Hosts file – add a record

We’ve seen how to read the Hosts file – this is how we add a record

function add-hostfilecontent {            
 param (            
 $file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"            
 if (-not (Test-Path -Path $file)){            
   Throw "Hosts file not found"            
 $data = Get-Content -Path $file             
 $data += "$IPAddress  $computer"            
 Set-Content -Value $data -Path $file -Force -Encoding ASCII             


Take an IP address and computer as parameters.  Test if the hosts file exists

Read the contents, add the new record and write back.

This ensures that the new record is actually on a new line all by itself

2 Responses to Hosts file – add a record

Leave a Reply