4.01.2015

Simplified Editing of Hosts file with PowerShell

 

Since the addition of User Account Control (UAC) in Windows vista and later editing the etc/hosts file has become a cumbersome multistep process:

For Windows 8

  1. Press the Windows key.
  2. Type Notepad in the search field.
  3. In the search right click Notepad and select Run as administrator.
  4. In Notepad, open the following file:
    C:\Windows\System32\Drivers\etc\hosts
  5. Make the necessary changes to the hosts file.
  6. Click File -> Save to save your changes.

PowerShell gives us a much cleaner way to accomplish this by creating a small but useful helper function:


[sourcecode language='powershell' ]
function Edit-Hostsfile {
Start-process "C:\Program Files (x86)\Notepad++\notepad++.exe" -Verb Runas -ArgumentList "-nosession", "C:\Windows\System32\drivers\etc\hosts"
}
[/sourcecode]


A couple of notes we use the Start-Process cmdlet with the RunAs verb to launch the process as admin. the -argumentlist passes a string[] of arguments to the process, in this case we use -nosession to tell npp to not reopen any existing sessions. We also provide the path to the host file. This script assumes you already have notepad++ installed to the default location. You could modify this file to use another editor such as PowerShell ISE or point to a different location if desired. Let me know how that works out for you.


Once this function has been created(I'd recommend saving it to your PowerShell profile) you can then run it like so:



[sourcecode language='powershell' ]
Edit-Hostsfile
[/sourcecode]


it will popup a notepad++ window running as administrator with just the hosts file then you can edit and save.


Drop me a line and let me know if you find this helpful.

No comments: