112

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.

Jeff
  • 1,623
  • 2
  • 12
  • 10
  • One hack would to be try to and do `echo > somefile` into a directory that would require admin privs. it'd produce a file as a sideffect, but you could check for collisions and create a unique filename as a workaround. – Marc B Nov 02 '11 at 18:52
  • 5
    possible duplicate of [Batch script: how to check for admin rights](http://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights) – npocmaka Sep 22 '14 at 23:09
  • 1
    [you can find a self-elevating batch here][1] [1]: http://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights/27083926#27083926 – Amr Ali Nov 23 '14 at 00:04
  • possible duplicate of [How to request Administrator access inside a batch file](http://stackoverflow.com/questions/1894967/how-to-request-administrator-access-inside-a-batch-file) – Jim Fell Aug 11 '15 at 18:24
  • 1
    @npocmaka the question you linked is actually the duplicate of this one ;) (2013 vs. 2011) – Matthieu Oct 03 '16 at 14:20

13 Answers13

112

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.

Ambrose Leung
  • 2,432
  • 1
  • 15
  • 25
  • That's functionally identical to Rushyo's answer, which used the AT command. – Jeff May 02 '13 at 22:13
  • 14
    On Windows 8.1, this is preferred to AT, as AT is deprecated. Using Rushyo's answer but substituting **AT** with **net session** or **net.exe session** works perfectly for me. – kayleeFrye_onDeck Dec 23 '14 at 00:23
  • 1
    This seems the easiest way to do this on command prompt (which is different than batch file, though). – enderland Oct 15 '15 at 15:28
  • 2
    Just prints `There are no entries in the list.` in Windows 10 Pro – gman Jan 17 '18 at 11:22
  • 1
    in a batch file use something like that: `net session >nul 2>&1 || (echo not admin&goto :eof)` – anilech Oct 23 '19 at 06:52
66

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.

Alexandre Rondeau
  • 2,527
  • 21
  • 30
Rushyo
  • 7,079
  • 3
  • 31
  • 42
  • 4
    The AT command is perfect! Your Google-fu is superior to my Google-fu. ;-) – Jeff Nov 02 '11 at 20:33
  • 2
    +1 @Rushyo, I extended your solution a bit and posted it here since that's the one I originally came across. Thanks! http://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights/8995407#8995407 – blak3r Jan 24 '12 at 22:48
  • 17
    `AT` doesn't work on Windows 8, but I've found a better solution. I've posted it as an answer on another question, here: http://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights#11995662. – mythofechelon Aug 17 '12 at 08:11
  • 4
    I recommend whoami /groups | findstr /b BUILTIN\Admin | findstr /c:"Enabled group" && echo "I have a admin!" - work on 95, 98, 2000, xp, vista, 7, 8! (From comment "I like Rushyo's sugesstion of using AT ...") – barwnikk Sep 02 '13 at 14:10
  • barwnikk, 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 – zumalifeguard Jun 18 '15 at 17:27
  • 1
    I like the `ping` to replace missing `sleep` :) – Matthieu Oct 03 '16 at 14:19
  • 1
    put the scripts into a cmd text file, run as normal, then as admin, both produced the same message "you are NOT Administrator. Exiting..." – Lin Song Yang Nov 16 '18 at 06:22
  • 1
    in win 10 for me this produced "you are NOT administrator" in both regular and elevated cmd prompt. This option did work: `@echo off whoami /groups | find "S-1-16-12288" > nul if %errorlevel% == 0 ( echo Welcome, Admin ) else ( echo Get lost, User )` – Chris L Mar 11 '20 at 15:46
  • @barwnikk this might work on english Windows installations. For example, here, you'd have to findstr for something like `VORDEFINIERT\Administratoren` and `Aktivierte Gruppe`. (not tested, though) – René Nyffenegger Mar 15 '20 at 18:42
  • 1
    Commad AT is deprecated in windows 10. Use command 'net session', see posts bellows. – lison Jun 10 '20 at 08:14
  • For PowerShell you can also used the "#Requires -RunAsAdministrator" at the beginning of your script to require elevation. – Ed Greaves Feb 18 '21 at 18:01
27

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

Harry Johnston
  • 33,445
  • 6
  • 56
  • 142
  • 1
    In polish version, I have: BUILTIN\Administratorzy, so, I recommend: whoami /groups | findstr /b BUILTIN\Admin | findstr /c:"Enabled group" && goto :isadministrator – barwnikk Sep 02 '13 at 14:09
  • @barwnikk, I recommend `whoami/groups` and then scanning the lines manually. Wouldn't take too long and the command fits in your brain. – Pacerier Feb 03 '15 at 11:33
  • @Pacerier: the point of the question is to detect elevation *in a batch file*. If a person is at the command line, all they need do is look at the window title, which always starts "Administrator:" if you are elevated. – Harry Johnston Feb 03 '15 at 20:04
  • @HarryJohnston, Wow didn't realize that. Does the "Administrator" title appear for all versions of windows? – Pacerier Feb 08 '15 at 17:59
  • @Pacerier: all current versions (Vista onwards). – Harry Johnston Feb 08 '15 at 19:54
  • 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 – zumalifeguard Jun 18 '15 at 17:44
  • @zumalifeguard: when I tested it, `whoami /groups` gave me the right information: that the group is present but disabled. My code checks that the group is enabled, so it shouldn't give you the wrong answer in your scenario. – Harry Johnston Jun 18 '15 at 21:58
  • I like this because it doesn't cause an error if user is not an admin. In a Visual Studio build event if there is an errorlevel the build will fail. This will code allows the build to proceed if user is not an admin. – Michael Fitzpatrick Jul 19 '16 at 21:57
  • Be aware that if you have a large list of groups this is too slow to be feasible. I just tried it on one machine (Win7 on a domain) and it took almost 30 seconds to gather the group list. – Euro Micelli Nov 30 '16 at 14:51
26

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)
geek_01
  • 405
  • 4
  • 7
12

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

Martin Binder
  • 990
  • 5
  • 4
  • 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 – zumalifeguard Jun 18 '15 at 17:45
8

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.

Hugh
  • 1,103
  • 1
  • 12
  • 22
  • 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 – zumalifeguard Jun 18 '15 at 17:44
7

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 )
user1438038
  • 5,319
  • 6
  • 49
  • 78
ipAlex
  • 71
  • 1
  • 1
6

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

GeoffH
  • 93
  • 1
  • 4
  • 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 – zumalifeguard Jun 18 '15 at 17:45
  • Thank you for this! The other "whoami" solution's didn't work for me on Windows 8.1. This one did. – Ryan Nov 24 '16 at 02:37
3

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
tivnet
  • 1,580
  • 14
  • 15
1

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.

user1
  • 143
  • 1
  • 8
  • This will only work if the user is a direct member of the Administrators local group. If the user is a member of a domain group (e.g., "Domain Admins") that is a member of the Administrators group, it won't work. – Harry Johnston Jun 18 '15 at 22:13
1

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
)
englebart
  • 477
  • 3
  • 9
1

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)

Wolfgang
  • 11
  • 2
0

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.