How to check in a batch file if you are running it elevated

Sometimes it is useful to check in a batch file if it was started from an elevated command prompt or as an administrator. I would like to share with you a trick which I am using to do this. The main idea of my trick is based on the value of the special environment variable %errorlevel% which stores the exit code for most console apps and commands. Let's see this in action.


When some console app finishes its job properly, the %errrorlevel% variable stores 0 as its value.
Open a new command prompt instance and run the "dir" command. After that, print the %errorlevel% value using the "echo" command:

echo %errorlevel%

It will produce 0 as the output.
dir errorlevel
Now, let's try to execute a command which requires elevation, from a regular non-elevated command prompt window. For example, let's try the openfiles command which requires admin rights.
If you print the %errorlevel% value, it will not be 0 because the openfiles command will fail to show opened files without administrator rights.
openfiles errorlevel 1
However, if you run it from an elevated command prompt (here is how to open an admin cmd prompt), it will show you opened files and will return 0, as expected.
openfiles errorlevel 0
Using this feature, it is possible to implement a simple check in the batch file:

@echo off
openfiles > NUL 2>&1 
if NOT %ERRORLEVEL% EQU 0 goto NotAdmin 
echo Hello from elevated command prompt 
goto End 
echo This command prompt is NOT ELEVATED 

Note that i use output redirection to suppress any output from the openfiles command. In the "> NUL 2>&1 part", the default output of the command is redirected to nowhere (NUL), and the error output is redirected to the standard output, i.e. to NUL too.
Instead of the openfiles command, you can use any command that requires elevation, for example, the net session command.
That's it.


3 thoughts on “How to check in a batch file if you are running it elevated

  1. myr4ik07

    Привет, прошу данный пост перевести на русскоязычную версию ваших ресурсов потому как с англ. не дружу, а при машинном переводе такую чепуху выдает, что смысл не могу поймать, а что то интересно )

    1. Sergey Tkachenko Post author

      Так писал уже ранее:

      1. myr4ik07

        о, пропустил видать, спасибо


Leave a Reply

Your email address will not be published. Required fields are marked *