bat file as administrator

July 11, 2013

I wanted to be able to run a bat file as administrator in order to have an easy shortcut to edit my windows hosts file. Here’s what I found

Shortcut to edit windows hosts file as Admin

Creating the batch file

Paste this in a new notepad file and save it somewhere as hosts.bat

takeown /f "%windir%\system32\drivers\etc\hosts" && icacls "%windir%\system32\drivers\etc\hosts" /grant administrators:F
%windir%\notepad.exe %windir%\system32\drivers\etc\hosts

Making it easy to access

Copy that file to c:\windows\system32\hosts.bat

How to access it

Click start then type “hosts” (no qutoes) and hit enter. You will notice you are not prompted for UAC but can save the file and the changes stick!

Shortcut to open Sublime Text 3 as admin

Create a file called sublime3.bat:

takeown /f "C:\Program Files\Sublime Text 3\sublime\_text.exe" && icacls "C:\Program Files\Sublime Text 3\sublime\_text.exe" /grant administrators:F
"C:\Program Files\Sublime Text 3\sublime_text.exe"

Making it easy to access

Copy that file to c:\windows\system32\sublime3.bat

How to access it

Click start then type “sublime3” (no qutoes) and hit enter. You will notice you are not prompted for UAC but can open/save files that normally require admin access (like windows hosts file)!

Alternative Method

Prompt for UAC via batch script

This script will create a .vbs file that checks for UAC and invoke a window asking for permissions if they don’t exist.

@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

REM now put the contents of your windows bat file here that you want to run

source