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.
1 2 3 4 5 6 7 8 9 10 11 |
@ECHO OFF set IS_ELEVATED=0 whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1 if %IS_ELEVATED% == 0 ( echo You must run the command prompt as administrator... pause exit /b 1 ) else { echo The command prompt is run as administrator... echo Place the code you want to execute in this else block } |
Instead of using the WHOAMI tool, you could also use the NET tool, which is also part of the Windows operating system.
1 2 3 4 5 6 7 8 9 10 |
@ECHO OFF net session >nul 2>&1 if %errorLevel% == 0 ( echo The command prompt is run as administrator... echo Place the code you want to execute in this else block ) else ( echo You must run the command prompt as administrator to install. pause exit /b 1 ) |
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). 🙂
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.
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