Windows - Batch Script - How To Check For Admin Rights - Stack Overflow
Windows - Batch Script - How To Check For Admin Rights - Stack Overflow
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
log in
tour
help
batch-file
cmd
admin
a_horse_with_no_name
flacs
136k
731
15
142
209
after you can change the right : [How to request Administrator access inside a batch file][1] [1]:
stackoverflow.com/questions/1894967/ Alban Apr 17 '13 at 15:22
Look here: "How can I auto-elevate my script or check for admin rights?" Matt Dec 3 '13 at 8:25
[stackoverflow.com/questions/4051883/ [1]: stackoverflow.com/questions/4051883/ Amr Ali Nov 23
'14 at 0:02
18 Answers
Issues
blak3r / Rushyo's solution works fine for everything except Windows 8. Running
8 results in:
AT
on Windows
%errorLevel% 1.
Research
So, I went searching for other commands that require elevated permissions.
rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes
of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied
access on both OSs when run with standard permissions.
Eventually, I did find one -
NET SESSION.
FOR
loops
AT
(Windows 8 incompatible) or
WHOAMI
(Windows XP incompatible).
Each of which have their own security, usability, and portability issues.
Testing
I've independently confirmed that this works on:
Windows XP, x86
Windows XP, x64
Windows Vista, x86
15
Implementation / Usage
So, to use this solution, simply do something like this:
@echo off
goto check_Permissions
:check_Permissions
echo Administrative permissions required. Detecting permissions...
net session >nul 2>&1
if %errorLevel% == 0 (
echo Success: Administrative permissions confirmed.
) else (
echo Failure: Current permissions inadequate.
)
pause >nul
Explanation
NET SESSION is a standard command used to "manage server computer connections. Used
without parameters, [it] displays information about all sessions with the local computer."
@echo off
goto check_Permissions
Jump to the
3.
:check_Permissions
code block
Run command
Hide visual output of command by
1. Redirecting the standard output (numeric handle 1 /
STDOUT)
stream to
nul
STDERR)
to the
if %errorLevel% == 0
If the value of the exit code ( %errorLevel%) is 0 then this means that no errors have
occurred and, therefore, the immediate previous command ran successfully
5.
else
If the value of the exit code ( %errorLevel%) is not 0 then this means that errors have
occurred and, therefore, the immediate previous command ran unsuccessfully
6. The code between the respective parenthesis will be executed depending on which criteria is
met
Screenshots
Windows 8
AT %errorLevel%:
NET SESSION
community wiki
12 revs
Ben Hooper
+1 Awesome job! Good research. Your post should deserves to be new accepted answer. blak3r Aug 28
'12 at 5:12
This solution normally works great, but if the "Server" (LanmanServer) service is stopped, the error code for
"Server service has not been started" is the same error code that you get for "Access is denied" resulting in
a false negative. In other words, there are cases where you can run this check with administrative privileges
and it will return the same error as it would without those privileges. Lectrode Nov 16 '13 at 3:51
@Lectrode I've posted an alternative solution which doesn't have the same issue:
stackoverflow.com/questions/4051883/ and31415 Jan 22 '14 at 23:04
This code returns a false positive (at least on Windows 7) if the user is a Power User. A Power User can
also "elevate" and then run net session successfully (ERRORLEVEL = 0) - but they don't actually have
admin rights. Using openfiles (see answer by Lucretius below) doesn't have this problem. E M Jan 14
at 17:32
Anders solution worked for me but I wasn't sure how to invert it to get the opposite (when you
weren't an admin).
Here's my solution. It has two cases an IF and ELSE case, and some ascii art to ensure people
actually read it. :)
M inimal Version
Rushyo posted this solution here: How to detect if CMD is running as Administrator/has elevated
privileges?
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
ECHO NOT AN ADMIN!
)
@rem ----[ This code block detects if the script is being running with admin
PRIVILEGES If it isn't it pauses and then quits]------echo OFF
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
echo ######## ######## ######## ####### ########
echo ##
##
## ##
## ##
## ##
##
echo ##
##
## ##
## ##
## ##
##
echo ###### ######## ######## ##
## ########
echo ##
## ## ## ## ##
## ## ##
echo ##
##
## ##
## ##
## ##
##
echo ######## ##
## ##
## ####### ##
##
echo.
echo.
echo ####### ERROR: ADMINISTRATOR PRIVILEGES REQUIRED #########
echo This script must be run as administrator to work properly!
echo If you're seeing this after clicking on a start menu icon, then right click
on the shortcut and select "Run As Administrator".
echo ##########################################################
echo.
PAUSE
EXIT /B 1
)
@echo ON
43
69
AT doesn't work on Windows 8, but I've found a better solution. I've posted it as an answer here, actually:
stackoverflow.com/questions/4051883/ (or you could just scroll down, whatever). mythofechelon Aug 16
'12 at 21:27
I wonder if two lines of if %errorLevel% == / EQU on first code-block is a TYPO.. please correct.
Ujjwal Singh Sep 4 '12 at 8:13
@UjjwalSingh It sure was. Thanks for catching. I've updated it. blak3r Sep 4 '12 at 23:05
Might want to replace the "Rushyo posted this solution here" with your comment about me now that you're
using my solution? :) mythofechelon Jan 16 '13 at 0:14
Doesn't work for the Domain Admins Group added to Administrators Group in the local machine and login
with the domain Admin user. M.C.Rohith Jan 17 '13 at 10:00
36
77
It seems that in some cases the test always failed, even after being elevated. In my case when the script
was called by my application. boileau Feb 13 '12 at 16:01
More issues
As pointed out by @Lectrode, if you try to run the net session command while the Server
service is stopped, you receive the following error message:
The Server service is not started.
More help is available by typing NET HELPMSG 2114
%errorLevel%
2.
Note The Server service is not started while in Safe Mode (with or without networking).
The fsutil dirty command requires admin rights to run, and will fail otherwise. %systemdrive%
is an environment variable which returns the drive letter where the operating system is installed.
The output is redirected to nul, thus ignored. The %errorlevel% variable will be set to 0 only
upon successful execution.
Here is what the documentation says:
Fsutil dirty
Queries or sets a volume's dirty bit. When a volume's dirty bit is set, autochk automatically
checks the volume for errors the next time the computer is restarted.
Syntax
fsutil dirty {query | set} <VolumePath>
Parameters
query
set
<VolumePath>
Remarks
A volume's dirty bit indicates that the file system may be in an inconsistent state. The dirty bit
can be set because:
The volume is online and it has outstanding changes.
Changes were made to the volume and the computer was shut down before the changes
were committed to the disk.
Corruption was detected on the volume.
If the dirty bit is set when the computer restarts, chkdsk runs to verify the file system integrity
and to attempt to fix any issues with the volume.
Examples
To query the dirty bit on drive C, type:
fsutil dirty query C:
Further research
While the solution above works from Windows XP onwards, it's worth adding that Windows 2000
and Windows PE (Preinstalled Environment) don't come with fsutil.exe, so we have to resort
to something else.
During my previous tests I noticed that running the
either result in:
sfc
The error output is first redirected to the standard output, which is then piped to the find
command. At this point we have to look for the only parameter that is supported in all Windows
version since Windows 2000: /SCANNOW. The search is case insensitive, and the output is
discarded by redirecting it to nul.
Here's an excerpt from the documentation:
Sfc
Scans and verifies the integrity of all protected system files and replaces incorrect versions
with correct versions.
Remarks
You must be logged on as a member of the Administrators group to run sfc.exe.
Sample Usage
Here are some paste-and-run examples:
Applies to
Windows 2000
Windows XP
Windows Vista
Windows 7
Windows 8
Windows 8.1
--Windows PE
edited Jan 22 '14 at 23:11
+1 Excellent solutions. The SFC solution in particular seems to be a reliable check for all of the operating
systems in question. If I come across any issues using either of these I will report them here. Lectrode
Jan 23 '14 at 3:53
For anyone looking to use the SFC check for all systems, you need to get a bit creative. For some reason,
starting with Windows 8 SFC outputs single characters only. In order to successfully parse the output, you
need to do the following: setlocal enabledelayedexpansion for /f "tokens=* delims=" %%s in
('sfc 2^>^&1^|MORE') do @set "output=!output!%%s" echo "%output%"|findstr /I
/C:"/scannow">nul 2>&1 (3 separate lines). This should work on Windows 2000 through Windows 2012
R2. On a side note, I prefer FINDSTR because it generally processes things more quickly than FIND.
Lectrode Jan 23 '14 at 8:46
Great work, @and31415! I haven't personally tested your fsutil solution yet but, from what I can see, it
seems a lot more flexible than my solution. Although, not quite as elegant, maybe. ;) I'm glad to see that,
between us, we're getting an excellent, easy, and flexible admin-detection solution pinned down. :)
alternative solution:
@echo off
pushd %SystemRoot%
openfiles.exe 1>nul 2>&1
if not %errorlevel% equ 0 (
Echo here you are not administrator!
) else (
Echo here you are administrator!
)
popd
Pause
Could you add an explanation to your answer? bjb568 Jun 17 '14 at 18:24
corrected more detail ... Lucretius Jun 17 '14 at 18:44
While this code might answer the question you should add some explanation on why it does so.
PlasmaHH Jun 17 '14 at 20:01
Yes! This works correctly even when the user is a Power User (unlike "net session"). There is no need for
the pushd/popd, though. Just running openfiles and checking ERRORLEVEL is enough. E M Jan 14
at 17:29
The snippet merges some good batch patterns together, especially (1) the admin test in this
thread by Ben Hooper and (2) the UAC activation read on BatchGotAdmin and cited on the batch
site by robvanderwoude (respect). (3) For the OS identificaton by "VER | FINDSTR pattern" I just
don't find the reference.)
(Concerning some very minor restrictions, when "NET SESSION" do not work as mentioned in
another answer- feel free to insert another of those commands. For me running in Windows safe
mode or special standard services down and such are not an important use cases- for some
admins maybe they are.)
edited Jul 30 at 16:21
Philm
1,107
11
The following tries to create a file in the Windows directory. If it suceeds it will remove it.
copy /b/y NUL %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
if errorlevel 1 goto:nonadmin
del %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
:admin
rem here you are administrator
goto:eof
:nonadmin
rem here you are not administrator
goto:eof
11
107
168
+1 because the accepted answer caused infinitely many command windows to be opened when the script
was called from my application. boileau Feb 13 '12 at 15:58
+1 for speed (this is a lot faster) orlp Jan 13 '13 at 18:53
I have two ways of checking for privileged access, both are pretty reliable, and very portable
across almost every windows version.
I think this is very reliable, because this commands are there since forever, and as @Dan said
"net session" can be disabled.
If you try to create a key on HKEY_LOCAL_MACHINE using default permissions you'll get
Access Denied and the ERRORLEVEL == 1, but if you run as Admin, it will print "command
executed successfully" and ERRORLEVEL == 0. Since the key already exists it have no effect
on the registry. This is probably the fastest way, and the REG is there for a long time, however
this behavior or the REG command may change in the future. And it's not avaliable on pre NT.
goto :eof
:requirePrivilegies
set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%
mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1
IF NOT %ERRORLEVEL%==0 (
echo ########## ERROR: ADMINISTRATOR PRIVILEGES REQUIRED ###########
echo # This script must be run as administrator to work properly! #
echo # Right click on the script and select "Run As Administrator" #
echo ###############################################################
pause>nul
exit
)
goto :eof
29
52
Some servers disable services that the command "net session" requires. This results in the
admin check always saying you don't have admin rights when you may have.
edited Mar 14 '13 at 7:37
24
49
11
23
Problem here is, that you check whether the user has admin rights. But the batch script could run without
admin rights. tanascius Mar 23 '12 at 10:30
Plus whoami isn't supported in Windows XP. mythofechelon Aug 16 '12 at 15:14
Also whoami /groups has an edge case where you get the wrong information. See
stackoverflow.com/questions/4051883/ zumalifeguard Jun 18 at 17:25
MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM=4,1>>Wins8x64Def.inf
Note: Checking with cacls for \system32\config\system will ALWAYS fail in WOW64, (for
example from %systemroot%\syswow64\cmd.exe / 32 bit Total Commander) so scripts that run
in 32bit shell in 64bit system will loop forever... Better would be checking for rights on Prefetch
directory:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\"
Win XP to 7 tested, however it fails in WinPE as in windows 7 install.wim there is no such dir nor
cacls.exe
Also in winPE AND wow64 fails check with openfiles.exe :
OPENFILES > nul
In Windows 7 it will errorlevel with "1" with info that "Target system needs to be 32bit operating
system"
Both check will probably also fail in recovery console.
What works in Windows XP - 8 32/64 bit, in WOW64 and in WinPE are: dir creation tests (IF
admin didn't carpet bombed Windows directory with permissions for everyone...) and
net session
and
reg add HKLM /F
checks.
Also one more note in some windows XP (and other versions probably too, depending on admin's
tinkering) depending on registry entries directly calling bat/cmd from .vbs script will fail with info
that bat/cmd files are not associated with anything...
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo
Calling cmd.exe with parameter of bat/cmd file on the other hand works OK:
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/C %~s0", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo
Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted
freeware).
Exit codes:
0 - Current user not member of Administrators group
1 - Current user member of Administrators and running elevated
2 - Current user member of Administrators, but not running elevated
answered Jun 17 '14 at 18:31
Bill_Stewart
3,460
15
@echo off
ver
set ADMDIR=C:\Users\Administrator
dir %ADMDIR% 1>nul 2>&1
echo [%errorlevel%] %ADMDIR%
if "%errorlevel%"=="0" goto main
:: further checks e.g. try to list the contents of admin folders
:: wherever they are stored on older versions of Windows
echo You need administrator privileges to run this script: %0
echo Exiting...
exit /b
:main
echo Executing with Administrator privileges...
@echo off
:start
set randname=%random%%random%%random%%random%%random%
md \windows\%randname% 2>nul
if %errorlevel%==0 (echo You're elevated!!!
goto end)
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
goto start
:end
rd \windows\%randname% 2>nul
pause >nul
Users will be annoyed with many more than 1 lines without this.
:start
<DL>:\Windows
In case the filename already exists, recreate the folder (otherwise the
not let this run).
goto end
command will
:end
>nul
and
2>nul
Yes I know that when you are logged in as the Administrator user (not a user with admin account type) you
will be always elevated but that's not a bug! erikkonstas Apr 22 at 14:55
The whoami /groups doesn't work in one case. If you have UAC totally turned off (not just
notification turned off), and you started from an Administrator prompt then issued:
runas /trustlevel:0x20000 cmd
will say you're elevated. It's wrong. Here's why it's wrong:
When running in this state, if IsUserAdmin (https://msdn.microsoft.com/enus/library/windows/desktop/aa376389(v=vs.85).aspx) returns FALSE and UAC is fully disabled,
and GetTokenInformation returns TokenElevationTypeDefault
(http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying-the-mandatory-integrity-level-for-asecurable-object-in-windows-vista.aspx) then the process is not running elevated, but whoami
/groups claims it is.
really, the best way to do this from a batch file is:
net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%
at
12
25
whoami /groups is not providing the wrong information. It's just that runas /trustlevel puts you in an
unexpected place: running without administrator privileges but with high integrity level. You can confirm this
with Process Explorer. (This may be a bug in runas but is not a bug in whoami.) Harry Johnston Jun
18 at 22:10
Harry, I hear what you're saying, but can you elaborate on this? I don't understand the comment with regard
to runas /trustlevel When you're a local admin, and UAC is disabled, issuing that runas command
from an admin prompt will put you into a "basic user" security context. While in that mode, you cannot
perform admin operations. Try "net session", or fsutil" or any other utility that requires administrator access.
However, "whoami /groups" tells you you're elevated. When you're not. The fact that calling
GetTokenInformation returns "TokenElevationTypeDefault" indicates that. zumalifeguard Jun 19 at 1:42
I'm not sure that I understand what you mean by "whoami /groups tells you you're elevated"; it doesn't
literally output the string "you're elevated", does it? What part of the output of whoami /groups are you
looking at? Harry Johnston Jun 19 at 2:07
Harry, I see I wasn't clear. First background, so you and I are on the same page. there a handful of tricks
people use in determining whether a command prompt is currently running in a state that has administrator
access. Common techniques are to use the built command such as fsutil, at, whoami and "net session".
Using "at" is deprecated. If you search this page, you will see examples using fsutil, whoami and "net
session". See here for more examples of whoami: stackoverflow.com/questions/7985755/ zumalifeguard
Jun 19 at 15:43
Also, using the phrase "running elevated" is not exactly correct. What I (and others) should say "running
with administrator privilege". If UAC is turned off, that's simply running while logged on as local admin but not
explicitly lowered trust-level such as with runas. When UAC is enabled, this means the user is running in an
elevated prompt. zumalifeguard Jun 19 at 15:45
####
#####
Michael Myers
99.2k
26
211
Artur Zgadzaj
250
What is that link supposed to be? Flagged as spam because of the link. mmgross Apr 7 at 22:57