Batch Script
Scripts
Batch Script Get Admin
·
Mike Hosker
Sometimes a batch script needs to do something that requires administrator privileges — modifying system files, changing registry keys, starting or stopping services. Rather than right-clicking and selecting "Run as administrator" every time, you can make the script self-elevate automatically.
Paste this snippet at the top of any .bat file. Anything you write below it will run as administrator, provided the user authenticates through the UAC prompt.
The Snippet
@echo off
:: Check for admin rights
net session >nul 2>&1
if %errorLevel% == 0 (
goto :admin
)
:: Not running as admin — create a temporary VBS to re-launch with elevation
set "vbs=%temp%\getadmin.vbs"
echo Set UAC = CreateObject^("Shell.Application"^) > "%vbs%"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%vbs%"
wscript "%vbs%"
del "%vbs%"
exit /b
:admin
:: Everything below here runs as administrator
How It Works
net sessionattempts a privileged network operation. If it fails with a non-zero error level, the script isn't running as admin.- A small VBScript file is written to
%temp%that callsShellExecutewith the"runas"verb — this triggers a UAC prompt. - The current script re-launches itself elevated. The VBS file is deleted.
- Execution continues from the
:adminlabel with full administrator rights.
Usage
@echo off
:: --- elevation snippet ---
net session >nul 2>&1
if %errorLevel% == 0 goto :admin
set "vbs=%temp%\getadmin.vbs"
echo Set UAC = CreateObject^("Shell.Application"^) > "%vbs%"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%vbs%"
wscript "%vbs%"
del "%vbs%"
exit /b
:admin
:: --- end elevation snippet ---
:: Your admin-level commands go here
sc stop "SomeService"
reg add "HKLM\SOFTWARE\Example" /v Setting /t REG_DWORD /d 1 /f
Notes
- If the user clicks No on the UAC prompt, the elevated instance never launches and the script exits silently
- The script window that triggered the UAC prompt will close — the elevated instance opens a new window
- Works on Windows Vista and later (anything with UAC)