Editing your Windows hosts file as administrator from a “simple” batch file or PowerShell command
Posted by jpluimers on 2022/07/07
Sometimes you want to edit your Windows hosts
file.
Next to that it is not in /etc/hosts
, but in %windir%\system32\drivers\etc\hosts.
, you also have to edit it elevated with an elevated Administrator token (see Source: User Account Control – Wikipedia).
The Windows GUI by default runs without that token, and for a keyboard person like me, doing the mouse clicking elevation can be cumbersome especially combined with the unintuitive path to the hosts
file.
Basically the below batch file executes this, but than elevated:
start notepad %windir%\system32\drivers\etc\hosts.
So I created a small batch file that does that for me: start notepad as an elevated user opening the correct file.
powershell -command "Start-Process notepad.exe -Verb runas -Args %windir%\system32\drivers\etc\hosts."
I named it edit-hosts-as-administrator.bat
, but consider naming it edit-hosts.bat
as the elevation is mandatory anyway.
It is based on by blog post Run cmd as elevated user (via: windows – How to run batch file command with elevated permissions? – Super User).
It helped setting up the localghost address explained in my blog post The spookback localghost address to resolve 👻.
That one in turn needed unicode support which I showed last week in Unicode symbols in a batch file – Stack Overflow.
Related:
- [Archive.is] Jeroen Wiert Pluimers on Twitter: “Hier heb ik ooit een batch file met de naam
edit-hosts.bat
voor gemaakt die automatisch om Administrator elevation vraagt. Dit is de inhoud ervan:powershell -command "Start-Process notepad.exe -Verb runas -Args %windir%\system32\drivers\etc\hosts."
Veel plezier ermee!… “ - [Wayback]
start
| Microsoft Docs - [Wayback]
Start-Process
(Microsoft.PowerShell.Management) – PowerShell | Microsoft Docs
–jeroen
Leave a Reply