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.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
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.
After some research (mostly on SO), 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 )
 my actual problem was elevation, but non-invasive checking is part of it:
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 )
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