I was just doing some work today where I needed to modify the content of the HOSTS file in Windows on a good bunch of devices. (This is the file being located in C:\Windows\System32\drivers\etc)
I figured this is something anybody might find useful, so I wanted to share the Powershell script I ended up creating for the purpose.
For your convenience, I’m also illustrating how this can be used in combination with ConfigMgr as this was a requirement for automation purposes 🙂
The use of the script is pretty straightforward. It’s created to accept parameters, so you don’t have to modify the content of the actual script on a need to need basis.
Adding a new entry to the hosts file is done by running the script with the -AddHost parameter:
- .\Edit-HostsFile.ps1 -AddHost -IP 192.168.1.1 -Hostname ftw.imab.dk
Removing an existing entry from the hosts file is done by running the script with the -RemoveHost parameter:
- .\Edit-HostsFile.ps1 -RemoveHost -Hostname ftw.imab.dk
Using the script with ConfigMgr is easy as well.
Create a package with a program running following command line:
- powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File .\Edit-HostsFile.ps1 -AddHost -IP 127.0.0.1 -Hostname ftw.imab.dk
Deploy it to the desired devices. In this example, this is done as an available deployment displaying in the Software Center.
You can also run the script directly in your task sequence as illustrated below.
The end result is a delicious HOSTS file now including your new modifications.