Check for an elevated command prompt in Batch

Today I was asked to look at a section of a batch script that checked if the command prompt or script was run with elevated permissions.
So I started both a normal and elevated CMD and started testing and scripting.
The solution that was used in the script utilized the WHOAMI command line tool, which is part of the Windows operating system.
However, we found that the script didn’t work on Windows 8 or any later Windows operating system.

Instead of using the WHOAMI tool, you could also use the NET tool, which is also part of the Windows operating system.

The benefit of this is that, by using the NET tool, the check for an elevated prompt works from Windows XP up to Windows 10 (technical preview). 🙂

2 comments

  1. Emin says:

    Nice approach with the net.exe tool 🙂

    The reason why the batch fails with whoami on Windows 8 is that the last findstr for “enabled group” returns nothing.

    Removing it will make it work on Windows 8.

    whoami /groups | findstr /b /c:”Mandatory LabelHigh Mandatory Level” > nul: && set IS_ELEVATED=1

    I’ve been using successfully a function in batch files on Windows 7, 8 and 8.1, here’s the code:

    8NUL 2>&1
    if /i “%errorlevel%”==”0” set _isAdmin=Y

    :: This is fot the System Mandatory Level Label
    “%systemroot%system32whoami.exe” /groups | find “S-1-16-16384” >NUL 2>&1
    if /i “%errorlevel%”==”0” set _isAdmin=Y

    8< —

    The main advantage is that it runs in any Language (although I've never tested) because it parses SID instead of labels.

  2. kasajian says:

    Agreed. Also whoami /groups has an edge case where you get the wrong information. See http://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights/30921854#30921854

Leave a Reply

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