This excellent answer demonstrates how to tell if a Windows batch script is being run with admin rights. For example, save the following to a batch file TestAdmin.bat
:
@echo off
echo Option 1: Use "net session"
net session >nul 2>&1
if %ERRORLEVEL% EQU 0 (echo Admin rights!) else (echo No admin rights...)
echo Option 2: Use "fsutil dirty"
fsutil dirty query %systemdrive% >nul
if %ERRORLEVEL% EQU 0 (echo Admin rights!) else (echo No admin rights...)
pause
Works correctly on a non-admin user account: Double-click the script and "No admin rights..." is printed twice. Right-click the script, choose "Run as administrator" and "Admin rights!" is printed.
However, my local account is a member of the Administrators
group and always displays "Admin rights!" no matter how the script is run.
Is it possible to tell the difference between a script run in two scenarios?
- run normally (i.e. double-clicked or run from a non-admin command window) by an Administrator account
- same script and same Administrator account, but using "Run as administrator" or run from an admin command window