Archive

Posts Tagged ‘ps1’

Changing Windows hosts file with Powershell

I’ve barely started looking into Powershell, but in in my mind, every developer needs to know something about it, at least if you use cmd.exe for anything today. I’ve already run into some problems, when I tried to script changes to the hosts file on my computer.

It seems that Windows 7 (at least my x64 installation with Norwegian regional settings) does not tolerate Powershell to create a hosts-file. I’ve tried with -encoding ASCII and other encodings, but Windows just ignores it, until I create a new one with Notepad.

The solution seems to use Clear-Content on the file and then append text to the end like this non-modifying code-example show. You typically want to do some search and replace or something else to change $content into $newcontent. You shouldn’t run it without backing up the hosts file first.

$file = "$env:windir\system32\drivers\etc\hosts"
$newcontent = $content
Clear-Content $file
$newcontent | Out-File $file -Encoding ASCII -append

I found this way of doing things after a lengthy search on the net, in a piece of source code by Mark Embling at github.

I’m still not sure why Windows doesn’t like hosts-file written directly by Powershell. I’ve looked at one working and one non-working file in a hex editor without seeing any differences (like byte order marks), but I’m sure there is an explanation somewhere. I guess this solution leaves the file almost like it was, without touching any attributes.

Categories: Scripting Tags: , ,