How do you update the hosts file on a Windows server with PowerShell?

Problem scenario:  Whenever you use PowerShell to append to the c:\windows\system32\drivers\etc\hosts file you get spaces before and after every character of every string.  The problem does not happen with ordinary text files.

To illustrate, here is a line of PowerShell code and take not of the destination flat file involved:
echo "8.8.8.8        continualintegration.com" >> c:\windows\system32\drivers\etc\hosts

The above code results in a line like this inside the file:
8 . 8 . 8 . 8         c o n t i n u a l i n t e g r a t i o n . c o m

Solution:  Copy the c:\windows\system32\drivers\etc\hosts to an intermediate file.  Update that file through your PowerShell script.  Then copy that file to c:\windows\system32\drivers\etc\hosts to overwrite it.

Leave a comment

Your email address will not be published. Required fields are marked *