How to detect if CMD is running as Administrator/has elevated privileges?

WindowsCommand LineCmd

Windows Problem Overview


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" is selected, so that doesn't work.

If there were a universally available command, which has no effect, but requires administrative privileges, then I could run that and check for an error code in order to test for privileges. So far, I haven't found such a command. The commands I have found seem to return a single, non-specific error code, which could indicate anything, and they're prone to failure for a variety of reasons.

I only care about Windows 7, though support of earlier operating systems would be nice.

Windows Solutions


Solution 1 - Windows

This trick only requires one command: type net session into the command prompt.

If you are NOT an admin, you get an access is denied message.

System error 5 has occurred.

Access is denied.

If you ARE an admin, you get a different message, the most common being:

There are no entries in the list.

From MS Technet:

> Used without parameters, net session displays information about all > sessions with the local computer.

Solution 2 - Windows

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.

Solution 3 - Windows

I like Rushyo's suggestion of using AT, but this is another option:

whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" && goto :isadministrator

This approach would also allow you to distinguish between a non-administrator and a non-elevated administrator if you wanted to. Non-elevated administrators still have BUILTIN\Administrators in the group list but it is not enabled.

However, this will not work on some non-English language systems. Instead, try

whoami /groups | findstr /c:" S-1-5-32-544 " | findstr /c:" Enabled group" && goto :isadministrator

(This should work on Windows 7 but I'm not sure about earlier versions.)

Solution 4 - Windows

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)

Solution 5 - Windows

The easiest way to do this on Vista, Win 7 and above is enumerating token groups and looking for the current integrity level (or the administrators sid, if only group memberhip is important):

Check if we are running elevated:

whoami /groups | find "S-1-16-12288" && Echo I am running elevated, so I must be an admin anyway ;-)

Check if we belong to local administrators:

whoami /groups | find "S-1-5-32-544" && Echo I am a local admin

Check if we belong to domain admins:

whoami /groups | find "-512 " && Echo I am a domain admin

The following article lists the integrity level SIDs windows uses: http://msdn.microsoft.com/en-us/library/bb625963.aspx

Solution 6 - Windows

Here's a slight modification of Harry's answer that focuses on elevated status; I'm using this at the start of an install.bat file:

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 to install.
	exit /b 1
)

This definitely worked for me and the principle seems to be sound; from MSFT's Chris Jackson:

> When you are running elevated, your token contains an ACE called Mandatory Label\High Mandatory Level. >

Solution 7 - Windows

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 )

Solution 8 - Windows

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 :)

Solution 9 - Windows

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

Solution 10 - Windows

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.

Solution 11 - Windows

Works for Win7 Enterprise and Win10 Enterprise

@if DEFINED SESSIONNAME (
    @echo.
    @echo You must right click to "Run as administrator"
    @echo Try again
    @echo.
    @pause
    @goto :EOF
)

Solution 12 - Windows

If you are running as a user with administrator rights then environment variable SessionName will NOT be defined and you still don't have administrator rights when running a batch file.

You should use "net session" command and look for an error return code of "0" to verify administrator rights.

Example;

  • the first echo statement is the bell character net session >nul 2>&1 if not %errorlevel%==0 (echo echo You need to start over and right-click on this file, echo then select "Run as administrator" to be successfull. echo.&pause&exit)

Solution 13 - Windows

Unfortunately, "S-1-5-32-544" that others have suggested is not proof of elevation.

Windows 10 and higher, a language independent approach is:

whoami /groups | find "S-1-16-12288"

this is the "High Mandatory Level", which is actually escalated.

Regular command prompt:

C:\> whoami /groups | find "S-1-16-12288"
C:\>

Administrator command prompt:

C:\> whoami /groups | find "S-1-16-12288"
Mandatory Label\High Mandatory Level                          Label            S-1-16-12288                                                                                                                                                     


C:\>

To use in a .bat file:

whoami /groups | find "S-1-16-12288" && set ELEVATED=true || set ELEVATED=false

You can also use this from powershell:

function is_elevated() {
  Param( [String] $ToGroup = "S-1-16-12288" )
  return [bool] ( whoami /groups | select-string $ToGroup )
}

for example:

PS> cd c:/temp
PS> set-content is-elevated.ps1 "return [bool] ( whoami /groups | sls S-1-16-12288 )"
PS> ./is-elevated.ps1
False
PS> start -verb runas powershell.exe
...
PS C:\Windows\system32> cd \temp
PS C:\temp> ./is-elevated.ps1
True

Solution 14 - Windows

Here's a simple method I've used on Windows 7 through Windows 10. Basically, I simply use the "IF EXIST" command to check for the Windows\System32\WDI\LogFiles folder. The WDI folder exists on every install of Windows from at least 7 onward, and it requires admin privileges to access. The WDI folder always has a LogFiles folder inside it. So, running "IF EXIST" on the WDI\LogFiles folder will return true if run as admin, and false if not run as admin. This can be used in a batch file to check privilege level, and branch to whichever commands you desire based on that result.

Here's a brief snippet of example code:

IF EXIST %SYSTEMROOT%\SYSTEM32\WDI\LOGFILES GOTO GOTADMIN
(Commands for running with normal privileges)

:GOTADMIN
(Commands for running with admin privileges)

Keep in mind that this method assumes the default security permissions have not been modified on the WDI folder (which is unlikely to happen in most situations, but please see caveat #2 below). Even in that case, it's simply a matter of modifying the code to check for a different common file/folder that requires admin access (System32\config\SAM may be a good alternate candidate), or you could even create your own specifically for that purpose.

There are two caveats about this method though:

  1. Disabling UAC will likely break it through the simple fact that everything would be run as admin anyway.

  2. Attempting to open the WDI folder in Windows Explorer and then clicking "Continue" when prompted will add permanent access rights for that user account, thus breaking my method. If this happens, it can be fixed by removing the user account from the WDI folder security permissions. If for any reason the user MUST be able to access the WDI folder with Windows Explorer, then you'd have to modify the code to check a different folder (as mentioned above, creating your own specifically for this purpose may be a good choice).

So, admittedly my method isn't perfect since it can be broken, but it's a relatively quick method that's easy to implement, is equally compatible with all versions of Windows 7, 8 and 10, and provided I stay mindful of the mentioned caveats has been 100% effective for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - WindowsAmbrose LeungView Answer on Stackoverflow
Solution 2 - WindowsRushyoView Answer on Stackoverflow
Solution 3 - WindowsHarry JohnstonView Answer on Stackoverflow
Solution 4 - Windowsgeek_01View Answer on Stackoverflow
Solution 5 - WindowsMartin BinderView Answer on Stackoverflow
Solution 6 - WindowsHughView Answer on Stackoverflow
Solution 7 - WindowsipAlexView Answer on Stackoverflow
Solution 8 - WindowsGeoffHView Answer on Stackoverflow
Solution 9 - WindowstivnetView Answer on Stackoverflow
Solution 10 - Windowsuser1View Answer on Stackoverflow
Solution 11 - WindowsenglebartView Answer on Stackoverflow
Solution 12 - WindowsWolfgangView Answer on Stackoverflow
Solution 13 - WindowskfsoneView Answer on Stackoverflow
Solution 14 - WindowsTorin DarkflightView Answer on Stackoverflow