How to Check if a Script is Running with Administrator Privileges
Many powerful administrative commands (sc, netsh, icacls, takeown, mklink, etc.) require elevated privileges to run. If your batch script attempts to use one of these commands without being "Run as Administrator," it will fail with an "Access is denied" error. A robust script should not just fail; it should first check its own permission level and either exit gracefully or, for interactive scripts, attempt to re-launch itself with the required permissions.
This guide will teach you a simple and highly reliable method for determining if your script is running with administrator rights. You will also learn the powerful "self-elevation" pattern, which allows a script to automatically prompt the user for elevation when needed.
The Challenge: No %IS_ADMIN% Variable
There is no built-in environment variable that tells a script its current privilege level. A script cannot simply ask, "Am I an administrator?" Instead, it must infer its status by trying to perform a harmless, read-only action that is known to succeed for administrators and fail for standard users.
The Core Method: Attempting an Admin-Only Operation
The classic and most reliable trick is to use the net session command.
- When run by an Administrator: The
net sessioncommand successfully executes (listing active network sessions, which is usually none) and returns anERRORLEVELof0. - When run by a Standard User: The command fails with an "Access is denied" error and returns a non-zero
ERRORLEVEL.
This gives us a perfect, predictable condition to check. It's safe because it doesn't change any system settings. An equally effective alternative is the fsutil dirty query C: command, which behaves the same way.
The Script: A Basic Administrator Check
This script uses the net session trick and checks the ERRORLEVEL to report on its own privilege level.
@ECHO OFF
ECHO --- Checking for Administrator Privileges ---
ECHO.
REM Attempt to run the admin-only command. Redirect output to NUL to keep the screen clean.
net session >nul 2>nul
IF %ERRORLEVEL% EQU 0 (
ECHO [SUCCESS] This script is running with Administrator privileges.
) ELSE (
ECHO [FAILURE] This script is running with Standard user privileges.
)
PAUSE
How the net session Trick Works
The key to this script is the line net session >nul 2>nul.
net session: The core command that we attempt to run.>nul: Redirects the standard output (like a success message) to the "null" device, hiding it.2>nul: Redirects the standard error output (like the "Access is denied" message) to the null device. This is crucial for keeping the output clean when the check fails.
Immediately after this command, %ERRORLEVEL% will be 0 for an admin and non-zero for a standard user, allowing the IF statement to correctly determine the status.
The Ultimate Solution: A Self-Elevating Script
This is the most professional and user-friendly pattern for any script that requires administrator rights. The script checks its own permissions. If it's not elevated, it uses a PowerShell one-liner to re-launch itself in a new, elevated window, which will trigger the standard Windows UAC (User Account Control) prompt.
@ECHO OFF
CLS
ECHO --- My Administrator Script ---
ECHO.
REM --- The Administrator Check ---
net session >nul 2>nul
IF %ERRORLEVEL% EQU 0 (
GOTO :AdminCode
)
ECHO [INFO] This script requires administrator privileges.
ECHO Requesting elevation...
ECHO.
REM --- The Self-Elevation Command ---
powershell -Command "Start-Process cmd -ArgumentList '/c %~f0 %*' -Verb RunAs"
REM --- Exit the non-elevated instance ---
EXIT /B
:AdminCode
REM =======================================================
REM Your script's main logic goes here.
REM This section will only be executed in an elevated window.
REM =======================================================
ECHO [SUCCESS] Now running with full administrator privileges.
ECHO.
ECHO Script's full path: %~f0
ECHO Arguments passed: %*
ECHO.
REM Example admin command:
sc query wuauserv
ECHO.
ECHO --- Script finished ---
PAUSE
How it works:
- The script first performs the
net sessioncheck. If it succeeds, it jumps to the:AdminCodesection. - If it fails, it prints a message and then executes the
powershellcommand.Start-Process cmd ... -Verb RunAs: This tells PowerShell to start a new process (cmd.exe) with the "RunAs" verb, which is what triggers the UAC elevation prompt.-ArgumentList '/c %~f0 %*': This is the crucial part. It tells the newcmd.exeto run (/c) our own script file (%~f0is the full path to the current script) and to pass along all of the original arguments (%*).
EXIT /B: This is essential. It immediately terminates the original, non-elevated script so you don't have two instances running.
Common Pitfalls and How to Solve Them
- Unattended Scripts: The self-elevation pattern is for interactive scripts only, as it requires a user to click "Yes" on the UAC prompt. An unattended, scheduled task that needs admin rights should be configured to "Run with highest privileges" in the Task Scheduler itself, not use this pattern.
- Infinite Loop: If the self-elevation command is written incorrectly, it's possible to create a loop where the script keeps re-launching itself. The
EXIT /Bis critical to preventing this.
Conclusion
Checking for administrator privileges is a cornerstone of writing safe and robust batch scripts that perform system-level tasks.
- The standard method is to use a read-only, admin-only command like
net sessionorfsutil dirty queryand check the%ERRORLEVEL%. - For any interactive script that requires elevation, the self-elevating pattern is the recommended best practice. It provides a seamless and user-friendly experience by automatically handling the UAC prompt.