Batch script: how to check for admin rights
Solution 1
You could always do something like this
mkdir "%windir%\system32\test" 2>nul
if "%errorlevel%" == "0" (rmdir "%windir%\system32\test" & echo Is admin) else (echo Not an Admin)
Not the best of ways but works for me all the time.
Solution 2
After some research (mostly on SO[1]), I found that net
is not always a good solution, it can show false negative results. But there is fsutil
available for WinXP to Win10. It's worth reading the whole insightful answer "More issues" to the question Batch script: how to check for admin rights there.
Here's the short answer for hurried users:
fsutil dirty query %systemdrive% >nul
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Running without
)
[1] my actual problem was elevation, but non-invasive checking is part of it:
command line - How to request Administrator access inside a batch file
windows - How to detect if CMD is running as Administrator/has elevated privileges?
Related videos on Youtube
solvease
Updated on September 18, 2022Comments
-
solvease over 1 year
How do I check if the current batch script has admin rights?
I know how to make it call itself with runas but not how to check for admin rights. The only solutions I've seen are crude hack jobs.
-
Naidim over 13 years@Bobby: That was asking how to do it in bash though.
-
Jjames over 13 years@Jason404: Wtf?! How the hack did I misread Batch for Bash? oO' @Tilka: My sincere apologies.
-
-
solvease over 13 yearsThat doesn't work when you are in a domain. And when I tried "net user %username% /domain" the Local Group Membership section didn't contain any groups although I have local admin rights. Strange...
-
solvease over 13 yearsPlus the output is localized.
-
utapyngo over 12 yearsBesides, one can run a batch file without administrator rights from an account who is in Administrators group (this especially relates Vista/7).
-
Pacerier about 9 yearsThis is a hack job which the OP is trying to avoid.............
-
Wolf about 7 yearsWell, also net sometimes fails
-
Wolf about 7 years
-
DavidPostill about 7 yearsThis doesn't work. It causes an infinite number of
cmd
shells to be opened. -
Acid about 6 yearsreally like it as it doesnt rely on any networking service - needed something 100% and this does it - btw knowing your drive isnt dirty is good aswell :o)