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:
dir echo %errorlevel%
It will produce 0 as the output.
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.
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.
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 :NotAdmin echo This command prompt is NOT ELEVATED :End
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.
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
If you like this article, please share it using the buttons below. It won't take a lot from you, but it will help us grow. Thanks for your support!
3 thoughts on “How to check in a batch file if you are running it elevated”
Привет, прошу данный пост перевести на русскоязычную версию ваших ресурсов потому как с англ. не дружу, а при машинном переводе такую чепуху выдает, что смысл не могу поймать, а что то интересно )
Так писал уже ранее: http://winreview.ru/kak-operedelit-v-komandnom-fajle-zapushhen-li-on-c-pravami-administratora/
о, пропустил видать, спасибо