If you find that Windows ignores your hosts
file try the following: open the file, select save as, and while saving it change encoding from Unicode (or whatever it is) to ANSI. Be sure to select the file type as “All files” so Notepad doesn’t append a “.txt” to the file name (and double check after saving as sometimes Notepad still appends a “.txt”).
How is this PowerShell related?
I was using Out-File
to put something into the hosts
file. Windows expects the hosts
file to be in ANSI encoding – and seems to ignore it otherwise – but Out-File
uses Unicode encoding by default; so the net result is that Windows ignores the resulting hosts
file. Even if I removed all the entries in it and made fresh ones for testing, since the file is still in Unicode encoding Windows ignores it. Finally, thanks to a great post I figured a workaround which led to realizing the problem.
Moral of the story: when writing to the hosts
file using Out-File
specify the encoding as ASCII. Like thus:
1 |
PS> Out-File -Encoding "ASCII" $hostsfile |
And if you are a PowerShell geek, you can avoid the longish method above of changing the hosts
file type to ANSI through something like this:
1 2 |
PS> $blah = Get-Content $hostsfile PS> $blah | Out-File -Encoding "ASCII" $hostsfile |
Easy peasy!