I needed to do this on several machines in a production environment and I wanted to make it as safe as possible. But what if you're dealing with a cluster of machines? What if you're not sure if you've already added some of the hosts entries? What if you need a script to automate the process? Don't worry, I've got you covered.Ī short while ago, I had a problem and I needed to roll out a quick fix in order to change the routing of traffic to certain domains, for reasons which we don't need to go into now. If you need to override DNS settings and route traffic for certain domains to specific IP addresses of your choosing then, if you don't want to mess around with DNS servers and/or proxies, the easiest way is to modify your hosts file. This needs to be used with extreme caution (although it does make a backup of the remote hosts file), but is useful if you are trying to get precisely the same hosts file onto several machines in one step. I'll also explain a few useful features of PowerShell scripts, such as the proper way to add support for the -WhatIf parameter.Īdditionally, there's an extra script which enables you to copy your modified hosts file to multiple machines. It could be argued that modifying the hosts file is not really how you should be doing things in a production environment, but it's easy to imagine various scenarios in which it could be useful. In other words, when you add a host to the hosts file, it won't add it if it's already there. The scripts do this by adding (or removing) entries to (or from) the hosts file and they do this idempotently, so you don't need to write any checks when adding or removing.
In this article I present a couple of simple PowerShell scripts which will modify the hosts file on one (or more) Windows machines, so that you can route traffic destined for certain domains to specific IP addresses with minimal fuss.