From inside a batch file, I would like to test whether I\'m running with Administrator/elevated privileges.
The username doesn\'t change when \"Run as Administrator\
A "not-a-one-liner" version of https://stackoverflow.com/a/38856823/2193477
@echo off
net.exe session 1>NUL 2>NUL || goto :not_admin
echo SUCCESS
goto :eof
:not_admin
echo ERROR: Please run as a local administrator.
exit /b 1
I know I'm really late to this party, but here's my one liner to determine admin-hood.
It doesn't rely on error level, just on systeminfo
:
for /f "tokens=1-6" %%a in ('"net user "%username%" | find /i "Local Group Memberships""') do (set admin=yes & if not "%%d" == "*Administrators" (set admin=no) & echo %admin%)
It returns either yes or no, depending on the user's admin status...
It also sets the value of the variable "admin" to equal yes or no accordingly.
I read many (most?) of the responses, then developed a bat file that works for me in Win 8.1. Thought I'd share it.
setlocal
set runState=user
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" > nul && set runState=admin
whoami /groups | findstr /b /c:"Mandatory Label\System Mandatory Level" > nul && set runState=system
echo Running in state: "%runState%"
if not "%runState%"=="user" goto notUser
echo Do user stuff...
goto end
:notUser
if not "%runState%"=="admin" goto notAdmin
echo Do admin stuff...
goto end
:notAdmin
if not "%runState%"=="system" goto notSystem
echo Do admin stuff...
goto end
:notSystem
echo Do common stuff...
:end
Hope someone finds this useful :)
Pretty much what others have put before, but as a one liner that can be put at the beginning of a batch command. (Well, usually after @echo off.)
net.exe session 1>NUL 2>NUL || (Echo This script requires elevated rights. & Exit /b 1)
the solution:
at >nul
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )
does not work under Windows 10
for all versions of Windows can be do so:
openfiles >nul 2>&1
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )
ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.
Found this solution here: http://www.robvanderwoude.com/clevertricks.php
AT > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO you are Administrator
) ELSE (
ECHO you are NOT Administrator. Exiting...
PING 127.0.0.1 > NUL 2>&1
EXIT /B 1
)
Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:
$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.