8

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.

  • @Bobby: That was asking how to do it in bash though. – paradroid Oct 29 '10 at 12:56
  • 1
    @Jason404: Wtf?! How the hack did I misread Batch for Bash? oO' @Tilka: My sincere apologies. – Bobby Oct 29 '10 at 13:04
6

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.

  • 2
    This is a hack job which the OP is trying to avoid............. – Pacerier Feb 3 '15 at 10:46
  • @Pacerier I think that's a joke! there are less invasive options like net and fsutil – Wolf Feb 3 '17 at 12:53
3

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:

  • really 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) – Acid Mar 19 '18 at 22:11
0

This is the best kludge I could think of, using standard commands:

net user %username% | findstr /r Administrator.
if %errorlevel% == 1 (
echo This is not an admin account
) else (
echo This is an admin account
)
  • That 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... – flacs Oct 29 '10 at 13:19
  • 1
    Plus the output is localized. – flacs Oct 29 '10 at 13:22
  • 1
    Besides, one can run a batch file without administrator rights from an account who is in Administrators group (this especially relates Vista/7). – utapyngo Nov 9 '11 at 4:41
  • Well, also net sometimes fails – Wolf Feb 3 '17 at 12:49
-1

You just need this one line at the top of your batches that require elevation. emphasis on "One Line"

nul 2>&1 fsutil dirty query %systemdrive% || echo CreateObject^("Shell.Application"^).ShellExecute "%~0", "ELEVATED", "", "runas", 1 > "getadmin.vbs" && "getadmin.vbs" && exit /b

  • 1
    This doesn't work. It causes an infinite number of cmd shells to be opened. – DavidPostill Mar 15 '17 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.