Batch script: how to check for admin rights
Asked Answered
A

26

350

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 or use external programs. Well, actually I don't care if it is a hack job as long as it works on Windows XP and newer.

Aguste answered 29/10, 2010 at 12:35 Comment(4)
after you can change the right : [How to request Administrator access inside a batch file][1] [1]: stackoverflow.com/questions/1894967/…Wil
Look here: "How can I auto-elevate my script or check for admin rights?"Slather
[stackoverflow.com/questions/4051883/… [1]: stackoverflow.com/questions/4051883/…Pence
See also: superuser.com/questions/667607/…Peeress
H
564

Issues

blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT on Windows 8 results in:

The AT command has been deprecated. Please use schtasks.exe instead.

The request is not supported.

(see screenshot #1) and will return %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. A true, clean, universal solution that doesn't involve:

  • the creation of or interaction with data in secure locations
  • analyzing data returned from FOR loops
  • searching strings for "Administrator"
  • using 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
  • Windows Vista, x64
  • Windows 7, x86
  • Windows 7, x64
  • Windows 8, x86
  • Windows 8, x64
  • Windows 10 v1909, x64

(see screenshot #2)

 

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

So, here's the basic process of my given implementation:

  1. @echo off
    • Disable displaying of commands
  2. goto check_Permissions
    • Jump to the :check_Permissions code block
  3. net session >nul 2>&1
    • Run command
    • Hide visual output of command by
      1. Redirecting the standard output (numeric handle 1 / STDOUT) stream to nul
      2. Redirecting the standard error output stream (numeric handle 2 / STDERR) to the same destination as numeric handle 1
  4. 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%:

[imgur]

 

NET SESSION on Windows XP x86 - Windows 8 x64:

[imgur]

 

Thank you, @Tilka, for changing your accepted answer to mine. :)

Hadria answered 29/10, 2010 at 12:35 Comment(10)
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.Tusche
@Tusche I've posted an alternative solution which doesn't have the same issue: stackoverflow.com/questions/4051883/…Illtempered
the dropbox link is outdated. how about pasting the bat file in gist.github.com ?Chui
not sure I understand why not just running an elevated cmd.exe (via a shortcut) instead of this netsession stuff that can fail. also, what does it mean that it works in xp. windows xp didn't have elevation, it had the opposite (very few knew about that opposite, though).Adaurd
oh OK elevated cmd.exe produces silly message box. but still what's this about Windows XP?Adaurd
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.Ray
You could also just do net session >NUL 2>NUL && echo is admin || echo isnt adminIdiocrasy
Also whoami /groups has an edge case where you get the wrong information. See stackoverflow.com/questions/4051883/…Amphiaster
This hangs the prompt if the network device isn't working fully (eg: Windows debugging). fltmc >nul 2>&1 works better in that regard.Tocharian
Also checked it with Microsoft Windows 10 x64 [Version 10.0.17763.615] - works like a charm. Thx for the answer ;-)Pharaoh
P
98

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

Minimal 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!
)

Version which adds an Error Messages, Pauses, and Exits

@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

Works on WinXP --> Win8 (including 32/64 bit versions).

EDIT: 8/28/2012 Updated to support Windows 8. @BenHooper pointed this out in his answer below. Please upvote his answer.

Polash answered 24/1, 2012 at 22:47 Comment(7)
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).Hadria
Might want to replace the "Rushyo posted this solution here" with your comment about me now that you're using my solution? :)Hadria
Doesn't work for the Domain Admins Group added to Administrators Group in the local machine and login with the domain Admin user.Operate
@Operate - I don't see why that'd matter. Are you sure you understand the script properly? It's checking for "elevated" privileges not whether the user logged in is an Administrator Role.Polash
ERRORLEVEL can be preset making the "IF %ERRORLEVEL% EQU 0" test useless. Consider something like: NET SESSION > nul 2>&1 && (echo good) || (echo bad)Kaluga
Thanks! I used it here: gist.github.com/L0Lock/564369212fac95a84a0f238dcb6dcc82Cookgeneral
This continues to work on Windows 10, where I'm using to allow itch.io customers to my Side Load UWP apps on Windows 10.Razid
I
60

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

In this case the %errorLevel% variable will be set to 2.

Note The Server service is not started while in Safe Mode (with or without networking).

Looking for an alternative

Something that:

  • can be run out of the box on Windows XP and later (32 and 64 bit);
  • doesn't touch the registry or any system file/folder;
  • works regardless of the system locale;
  • gives correct results even in Safe Mode.

So I booted a vanilla Windows XP virtual machine and I started scrolling through the list of applications in the C:\Windows\System32 folder, trying to get some ideas. After trials and errors, this is the dirty (pun intended) approach I've come up with:

fsutil dirty query %systemdrive% >nul

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           Queries the specified volume's dirty bit.
set             Sets the specified volume's dirty bit.
<VolumePath>    Specifies the drive name followed by a colon or GUID.

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 sfc command without any parameters would either result in:

  • an error, if you didn't have enough privileges;
  • a list of the available parameters and their usage.

That is: no parameters, no party. The idea is that we can parse the output and check if we got anything but an error:

sfc 2>&1 | find /i "/SCANNOW" >nul

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:

Windows XP and later

@echo off

call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)

pause >nul
exit /b

:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b

Windows 2000 / Windows PE

@echo off

call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)

pause >nul
exit /b

:isAdmin
sfc 2>&1 | find /i "/SCANNOW" >nul
exit /b

Applies to

  • Windows 2000
  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8
  • Windows 8.1
    ---
  • Windows PE
Illtempered answered 22/1, 2014 at 22:55 Comment(7)
+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.Tusche
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.Tusche
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. :)Hadria
When running FSUTIL you can leave out the drive letter and just run fsutil dirty query >nul when elevated this returns some help text and %errorlevel%=0Onomastic
@ss64 Windows 10 no longer returns a nonzero error level for fsutil dirty query >nul, however fsutil dirty query %systemdrive% >nul still worksCharil
If one wants to negate, do it like this: if NOT .%errorlevel% == .0.Hutton
The default user account in Windows PE is always "administrator" with full administrative rights and UAC disabled. It's probably possible to modify this behavior; e.g. create a user account without administrative rights and to log this on automatically, but would require quite an effort.Constituent
Q
24

two more ways - fast and backward compatible .

fltmc >nul 2>&1 && (
  echo has admin permissions
) || (
  echo has NOT admin permissions
)

fltmc command is available on every windows system since XP so this should be pretty portable.


One more really fast solution tested on XP,8.1,7 - there's one specific variable =:: which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains = in it's name this is comparatively reliable way to check for admin permission (it does not call external executables so it performs well)

setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! ( 
   echo has NOT admin permissions
) else (
   echo has admin permissions
)

If you want use this directly through command line ,but not from a batch file you can use:

set ^"|find "::"||echo has admin permissions
Quadrennial answered 1/2, 2015 at 22:41 Comment(6)
Epic... Does the set "dv==::" solution have any drawbacks/limitations?Ryder
Well, for some reason the !dv! method always says i'm Administrator, while i haven't right-clicked "Run as Administrator" the batch file (Windows 10). I really thought this method was flawless. I loved this method because it isn't depended on external programs. Now i'm sad and i don't know what's making it fail/unreliable for me :(Ryder
@copyitright - I had no win10 machine to test it there :( . Though existence of =:: variable is rather a bug - it represents a not existing drive , so probably it was fixed in win10.Quadrennial
They've probably patched it yes. It was fun while it lasted.Ryder
I see =:: is defined for non admin CMD on windows 10 1709. Anyway it is not a reliable way, you can easily force it to be defined even on admin CMD sessions: subst :: c:\ & for %a in (::) do %a & set,Peripeteia
FLTMC is my favourite solution here. Doesn't rely on networking features, so there isn't weird edge cases like no network card/service running/hangs from it waiting on networking etc. Simple, one word, no arguments, works back to XP, doesn't rely on a bug (like the set "dv==::" solution.) And it's intended purpose is simply to list out the installed drivers, so it shouldn't have any weird side effects either, like creating admin-only files or registry keys can.Pulchia
S
20

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
Stuff answered 17/6, 2014 at 17:43 Comment(6)
Could you add an explanation to your answer?Nigelniger
While this code might answer the question you should add some explanation on why it does so.Octameter
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.Ray
I've been using this solution and it's been working nice. The problem is that openfiles.exe doesn't work in WinPE, so the script will always return that user is not admin.Duchess
Documentation for openfiles.exe can be found on technet.microsoft.com/de-de/library/bb490961.aspx. 1> and 2>&1 are explained on microsoft.com/resources/documentation/windows/xp/all/proddocs/…. nul refers to the null deviceLathrope
will get ERROR: The target system must be running a 32 bit OS. on 32bit cmd on 64bit system.Franchot
A
17
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
 echo admin...
)
Absorption answered 29/10, 2010 at 18:51 Comment(1)
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.Shortcake
W
16

I have two ways of checking for privileged access, both are pretty reliable, and very portable across almost every windows version.

1. Method

set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%

mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

This is one of the most reliable methods, because of its simplicity, and the behavior of this very primitive command is very unlikely to change. That is not the case of other built-in CLI tools like net session that can be disabled by admin/network policies, or commands like fsutils that changed the output on Windows 10.

* Works on XP and later

2. Method

REG ADD HKLM /F>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

Sometimes you don't like the idea of touching the user disk, even if it is as inoffensive as using fsutils or creating a empty folder, is it unprovable but it can result in a catastrophic failure if something goes wrong. In this scenario you can just check the registry for privileges.

For this you can 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.

* It's not avaliable on pre NT (Win 9X).

* Works on XP and later


Working example

A script that clear the temp folder

@echo off
:main
    echo.
    echo. Clear Temp Files script
    echo.

    call :requirePrivilegies

    rem Do something that require privilegies

    echo. 
    del %temp%\*.*
    echo. End!

    pause>nul
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
Washroom answered 27/4, 2013 at 4:57 Comment(2)
I really like the registry method. I can actually remember it, don't have to look it up every time I use it.Clinometer
“Since the key already exists it have no effect on the registry” is not entirely accurate. REG ADD HKLM /F will create an empty string as the key's default value. If there's a default value associated with HKLM (not today, but say in the future) then it will be overwritten with an empty string. In short, it does have/leave an effect.Tswana
D
13

Not only check but GETTING admin rights automatically
aka Automatic UAC for Win 7/8/8.1 ff.
: The following is a really cool one with one more feature: This batch snippet does not only check for admin rights, but gets them automatically! (and tests before, if living on an UAC capable OS.)

With this trick you don´t need longer to right klick on your batch file "with admin rights". If you have forgotten, to start it with elevated rights, UAC comes up automatically! Moreoever, at first it is tested, if the OS needs/provides UAC, so it behaves correct e.g. for Win 2000/XP until Win 8.1- tested.

@echo off
REM Quick test for Windows generation: UAC aware or not ; all OS before NT4 ignored for simplicity
SET NewOSWith_UAC=YES
VER | FINDSTR /IL "5." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO
VER | FINDSTR /IL "4." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO


REM Test if Admin
CALL NET SESSION >nul 2>&1
IF NOT %ERRORLEVEL% == 0 (

    if /i "%NewOSWith_UAC%"=="YES" (
        rem Start batch again with UAC
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
        "%temp%\getadmin.vbs"
        del "%temp%\getadmin.vbs"
        exit /B
    )

    rem Program will now start again automatically with admin rights! 
    rem pause
    goto :eof
)

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

Derange answered 6/2, 2013 at 12:39 Comment(4)
This is great! Note one thing - calling it from the Visual Basic works like start - it opens the script in a new window. If you want to see the results - add a pause at the end of your script. Also, it's hard to detect, when we're "staying" elevated, and when there is a rerun. You can use a command line argument for that: github.com/tgandor/meats/blob/master/lang_lawyer/cmd/…Lasky
@Philm: What if UAC requires the user to enter their password? I assume this code won't give them Admin rights automatically without having the user enter their password first ;-)Ryder
@copyitright. No, of course not. But if password necessary or not is not a difference here: What I meant with "automatically" is of course, that the script triggers Windows to ASK automatically for the rights, not more. Without a construction like this, the batch script would fail, if started by double click or similar. To avoid that, the user would have to know in advance that the script requires elevated rights and had to start it like that.Derange
So my script just allows the author of a batch files to shift the moment of necessary elevation to a point during the batch execution which he or she wants. Or in other words: To allow more convenient execution by normal "doubleclick". Because I considered such batchfiles normally used by professionals or users with very good knowledge of underlying Windows technologiy, I didn't explain that in detail.Derange
S
9

In the batch script Elevate.cmd (see this link), which I have written to get admin rights, I have done it the following way:

@echo off

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

and the rest of the script might look like this:

:getPrivileges
  rem need to get admin rights, check batch script Elevate.cmd to see how to do that
  echo You have no admin rights. Cannot continue.
  goto end

:gotPrivileges
  echo You have admin rights. Continuing...
  rem *** do your admin tasks here ***

:end
  pause

This is tested for Windows 7, 8, 8.1, 10 and even Windows XP and does not need any resource such as a special directory, file or registry key.

It uses the fact that the command NET FILE needs to have admin rights to run and will return an error level 0 if it ran successfully (and detected admin rights), otherwise it returns an error level > 0. Any messages are suppressed by 1>NUL 2>NULL.

The advantage NET FILE has is, that it will not change anything on the system to detect admin rights (like other solutions trying to probe admin rights by creating registry keys or files/directories in protected areas).

Slather answered 11/1, 2019 at 16:0 Comment(0)
C
8

The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:

@echo off

REM  Calling verify with no args just checks the verify flag,
REM   we use this for its side effect of setting errorlevel to zero
verify >nul

REM  Attempt to read a particular system directory - the DIR
REM   command will fail with a nonzero errorlevel if the directory is
REM   unreadable by the current process.  The DACL on the
REM   c:\windows\system32\config\systemprofile directory, by default,
REM   only permits SYSTEM and Administrators.
dir %windir%\system32\config\systemprofile >nul 2>nul

REM  Use IF ERRORLEVEL or %errorlevel% to check the result
if not errorlevel 1 echo has Admin privs
if     errorlevel 1 echo has only User privs

This method only uses CMD.exe builtins, so it should be very fast. It also checks for the actual capabilities of the process rather than checking for SIDs or group memberships, so the effective permission is tested. And this works as far back as Windows 2003 and XP. Normal user processes or nonelevated processes fail the directory probe, where as Admin or elevated processes succeed.

Cogwheel answered 7/9, 2016 at 19:23 Comment(2)
copyitright pointed out that this is unreliable. If you visit %windir%\system32\config\systemprofile in an Explorer window and approve with UAC the CMD window can successfully dir the contents. Leading you to think you have elevation when you do not.Eu
I been trying all methods here. I run into several issues with a big script, since sometimes is ran under a program that is run as an Admin user, but not ran as administrator. so ALL checks here somehow passed as admin, but then the script couldnt access some path of the registry. This was the truly only method that worked. Is pretty pretty uncommon that the user goes to %windir%\system32\config\systemprofil and accept the UAC so the @TylerSzabo "complain" is pretty exagerattedPoet
A
6

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

you will be running non-elevated, but issuing:

whoami /groups

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/en-us/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-a-securable-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%

You should do net session twice because if someone did an at before hand, you'll get the wrong information.

Amphiaster answered 18/6, 2015 at 17:24 Comment(9)
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.)Platen
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.Amphiaster
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?Platen
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/…Amphiaster
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.Amphiaster
My point is that your answer as currently written says that whoami /groups is giving you the wrong information, which it isn't. If what you actually mean that whoami /groups is giving you information that can be misinterpreted, you should say that instead, and provide details.Platen
Harry, I do appreciate your feedback. So let's talk about the specifics. "whoami /groups" reports that the user is the Group called "Mandatory Label\High Mandatory Level". That is incorrect when the user is not running with admin privilege, which is the case. It is not that it is being misinterpreted. The user cannot have a High Mandatory Level while not running in an administrative context, which can be verified with the GetTokenInformation method call.Amphiaster
I don't believe the kernel actively prevents a token that doesn't have admin access from having a high integrity level. I didn't try writing code of my own to check the details, but Process Explorer confirmed what whoami /groups was saying, and it seems unlikely that they would both be wrong. Can you show the code you're using to verify this? I can try it out on my system and see whether I get the same results or not. (NB: tokens constructed by the operating system should always have high integrity if and only if they have admin access, which is why I said this may be a bug in runas.)Platen
I've written up and posted some code to try this out.Platen
A
5

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

Note that 06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 is a GUID that was generated today and it is assumed to be improbable to conflict with an existing filename.

Aplenty answered 29/10, 2010 at 12:49 Comment(1)
was generated today and it is assumed to be improbable to conflict with an existing filename. except if two people use this codeWashroom
M
3
whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
  echo ...  connected as admin
)
Mojave answered 15/1, 2012 at 18:56 Comment(3)
Problem here is, that you check whether the user has admin rights. But the batch script could run without admin rights.Damaris
Plus whoami isn't supported in Windows XP.Hadria
Also whoami /groups has an edge case where you get the wrong information. See stackoverflow.com/questions/4051883/…Amphiaster
A
2

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.

Adigun answered 14/3, 2013 at 5:43 Comment(0)
E
2

Edit: copyitright has pointed out that this is unreliable. Approving read access with UAC will allow dir to succeed. I have a bit more script to offer another possibility, but it's not read-only.

reg query "HKLM\SOFTWARE\Foo" >NUL 2>NUL && goto :error_key_exists
reg add "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_not_admin
reg delete "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_failed_delete
goto :success

:error_failed_delete
  echo Error unable to delete test key
  exit /b 3
:error_key_exists
  echo Error test key exists
  exit /b 2
:error_not_admin
  echo Not admin
  exit /b 1
:success
  echo Am admin

Old answer below

Warning: unreliable


Based on a number of other good answers here and points brought up by and31415 I found that I am a fan of the following:

dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin

Few dependencies and fast.

Eu answered 30/12, 2016 at 21:50 Comment(1)
This solution used to work for me but since i've browsed to the location and accessed the folder you need elevated privileges for, the ERRORLEVEL/exit code is always 0 now, despite running the script as standard user.Ryder
S
2

PowerShell anyone?

param (
    [string]$Role = "Administrators"
)

#check for local role

$identity  = New-Object Security.Principal.WindowsIdentity($env:UserName)
$principal = New-Object Security.Principal.WindowsPrincipal($identity)

Write-Host "IsInRole('$Role'): " $principal.IsInRole($Role)

#enumerate AD roles and lookup

$groups = $identity::GetCurrent().Groups
foreach ($group in $groups) {
    $trans = $group.Translate([Security.Principal.NTAccount]);
    if ($trans.Value -eq $Role) {
       Write-Host "User is in '$Role' role"
    }
}
Sleeping answered 25/1, 2017 at 22:57 Comment(0)
L
2

A collection of the four seemingly most compatible methods from this page. The first one's really quite genius. Tested from XP up. Confusing though that there is no standard command available to check for admin rights. I guess they're simply focusing on PowerShell now, which is really useless for most of my own work.

I called the batch 'exit-if-not-admin.cmd' which can be called from other batches to make sure they don't continue execution if the required admin rights are not given.

rem Sun May 03, 2020

rem Methods for XP+ used herein based on:
rem https://mcmap.net/q/13763/-batch-script-how-to-check-for-admin-rights
goto method1

:method1
setlocal enabledelayedexpansion
set "dv==::"
if defined !dv! goto notadmin
goto admin

:method2
call fsutil dirty query %SystemDrive% >nul
if %ERRORLEVEL%==0 goto admin
goto notadmin

:method3
net session >nul 2>&1
if %ERRORLEVEL%==0 goto admin
goto notadmin

:method4
fltmc >nul 2>&1 && goto admin
goto notadmin

:admin
echo Administrator rights detected
goto end

:notadmin
echo ERROR: This batch must be run with Administrator privileges
pause
exit /b
goto end

:end```
Landlord answered 3/5, 2020 at 18:11 Comment(0)
N
1

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
Negrito answered 21/10, 2013 at 11:0 Comment(0)
P
1

Literally dozens of answers in this and linked questions and elsewhere at SE, all of which are deficient in this way or another, have clearly shown that Windows doesn't provide a reliable built-in console utility. So, it's time to roll out your own.

The following C code, based on Detect if program is running with full administrator rights, works in Win2k+1, anywhere and in all cases (UAC, domains, transitive groups...) - because it does the same as the system itself when it checks permissions. It signals of the result both with a message (that can be silenced with a switch) and exit code.

It only needs to be compiled once, then you can just copy the .exe everywhere - it only depends on kernel32.dll and advapi32.dll (I've uploaded a copy).

chkadmin.c:

#include <malloc.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib,"Advapi32.lib")

int main(int argc, char** argv) {
    BOOL quiet = FALSE;
    DWORD cbSid = SECURITY_MAX_SID_SIZE;
    PSID pSid = _alloca(cbSid);
    BOOL isAdmin;

    if (argc > 1) {
        if (!strcmp(argv[1],"/q")) quiet=TRUE;
        else if (!strcmp(argv[1],"/?")) {fprintf(stderr,"Usage: %s [/q]\n",argv[0]);return 0;}
    }

    if (!CreateWellKnownSid(WinBuiltinAdministratorsSid,NULL,pSid,&cbSid)) {
        fprintf(stderr,"CreateWellKnownSid: error %d\n",GetLastError());exit(-1);}

    if (!CheckTokenMembership(NULL,pSid,&isAdmin)) {
        fprintf(stderr,"CheckTokenMembership: error %d\n",GetLastError());exit(-1);}

    if (!quiet) puts(isAdmin ? "Admin" : "Non-admin");
    return !isAdmin;
}

1MSDN claims the APIs are XP+ but this is false. CheckTokenMembership is 2k+ and the other one is even older. The last link also contains a much more complicated way that would work even in NT.

Peeress answered 5/12, 2016 at 13:33 Comment(0)
N
1

Here is another one to add to the list ;-)

(attempt a file creation in system location)

CD.>"%SystemRoot%\System32\Drivers\etc\_"
MODE CON COLS=80 LINES=25

IF EXIST "%SystemRoot%\System32\Drivers\etc\_" (

  DEL "%SystemRoot%\System32\Drivers\etc\_"

  ECHO Has Admin privileges

) ELSE (

  ECHO No Admin privileges

)

The MODE CON reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.

Nidanidaros answered 23/4, 2017 at 3:19 Comment(0)
D
0

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

Dogfight answered 17/6, 2014 at 18:31 Comment(0)
D
0
@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...
Davide answered 29/11, 2014 at 22:11 Comment(0)
S
0
@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

I will explain the code line by line:

@echo off

Users will be annoyed with many more than 1 lines without this.

:start

Point where the program starts.

set randname=%random%%random%%random%%random%%random%

Set the filename of the directory to be created.

md \windows\%randname% 2>nul

Creates the directory on <DL>:\Windows (replace <DL> with drive letter).

if %errorlevel%==0 (echo You're elevated!!!
goto end)

If the ERRORLEVEL environment variable is zero, then echo success message.
Go to the end (don't proceed any further).

if %errorlevel%==1 (echo You're not elevated :(:(
goto end)

If ERRORLEVEL is one, echo failure message and go to the end.

goto start

In case the filename already exists, recreate the folder (otherwise the goto end command will not let this run).

:end

Specify the ending point

rd \windows\%randname% 2>nul

Remove the created directory.

pause >nul

Pause so the user can see the message.

Note: The >nul and 2>nul are filtering the output of these commands.

Starknaked answered 22/4, 2015 at 14:50 Comment(1)
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!Starknaked
W
0

net user %username% >nul 2>&1 && echo admin || echo not admin

Whorish answered 9/12, 2015 at 12:1 Comment(3)
This seems to be wrong, it shows if a user has administrator rights, but this is not related to the question if the current cmd.exe is run with admin rightsSpherical
nope, it shows whether current cmd.exe has administrative access to users database or not, so it works even in the case when "net session" doesn't. alternatively, "net config >nul 2>&1 && echo admin || echo not admin" does the job. Both constructions tested successfully on windows xp under guest, power user and administarative accounts with LanmanServer stopped (errorlevel 2 for cmd.exe run under guest and power user, errorlevel 0 for cmd.exe under admin rights). Will it work in Vista and later with abovementioned UAC issues - i don't know, so it would be nice if someone could test it.Whorish
I tested with two cmd windows (win7x64), started with and without admin rights. In both cases it shows adminSpherical
C
-1

Here's my 2-pennies worth:

I needed a batch to run within a Domain environment during the user login process, within a 'workroom' environment, seeing users adhere to a "lock-down" policy and restricted view (mainly distributed via GPO sets).

A Domain GPO set is applied before an AD user linked login script Creating a GPO login script was too per-mature as the users "new" profile hadn't been created/loaded/or ready in time to apply a "remove and/or Pin" taskbar and Start Menu items vbscript + add some local files.

e.g.: The proposed 'default-user' profile environment requires a ".URL' (.lnk) shortcut placed within the "%ProgramData%\Microsoft\Windows\Start Menu\Programs*MyNewOWA.url*", and the "C:\Users\Public\Desktop\*MyNewOWA.url*" locations, amongst other items

The users have multiple machines within the domain, where only these set 'workroom' PCs require these policies.

These folders require 'Admin' rights to modify, and although the 'Domain User' is part of the local 'Admin' group - UAC was the next challenge.

Found various adaptations and amalgamated here. I do have some users with BYOD devices as well that required other files with perm issues. Have not tested on XP (a little too old an OS), but the code is present, would love feed back.

    :: ------------------------------------------------------------------------
    :: You have a royalty-free right to use, modify, reproduce and distribute
    :: the Sample Application Files (and/or any modified version) in any way
    :: you find useful, provided that you agree that the author provides
    :: no warranty, obligations or liability for any Sample Application Files.
    :: ------------------------------------------------------------------------

    :: ********************************************************************************
    ::* Sample batch script to demonstrate the usage of RunAs.cmd
    ::*
    ::* File:           RunAs.cmd
    ::* Date:           12/10/2013
    ::* Version:        1.0.2
    ::*
    ::* Main Function:  Verifies status of 'bespoke' Scripts ability to 'Run As - Admin'
    ::*                 elevated privileges and without UAC prompt
    ::*
    ::* Usage:          Run RunAs.cmd from desired location
    ::*         Bespoke.cmd will be created and called from C:\Utilities location
    ::*         Choose whether to delete the script after its run by removing out-comment
    ::*                 (::) before the 'Del /q Bespoke.cmd' command
    ::*
    ::* Distributed under a "GNU GPL" type basis.
    ::*
    ::* Revisions:
    ::* 1.0.0 - 08/10/2013 - Created.
    ::* 1.0.1 - 09/10/2013 - Include new path creation.
    ::* 1.0.2 - 12/10/2013 - Modify/shorten UAC disable process for Admins
    ::*
    ::* REFERENCES:
    ::* Sample "*.inf" secpol.msc export from Wins 8 x64 @ bottom, 
    ::* Would be default but for 'no password complexities'
    ::*
    ::* To recreate UAC default: 
    ::* Goto:Secpol, edit out Exit, modify .inf set, export as "Wins8x64.inf" 
    ::* and import using secedit cmd provided
    ::*
    :: ********************************************************************************

    @echo off & cls
    color 9F
    Title RUN AS
    Setlocal
    :: Verify local folder availability for script
    IF NOT EXIST C:\Utilities (
        mkdir C:\Utilities & GOTO:GenBatch
    ) ELSE (
        Goto:GenBatch
    )
    :GenBatch
    c:
    cd\
    cd C:\Utilities
    IF NOT EXIST C:\Utilities\Bespoke.cmd (
        GOTO:CreateBatch
    ) ELSE (
        Goto:RunBatch
    )
    :CreateBatch
    Echo. >Bespoke.cmd
    Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
    Echo :: You have a royalty-free right to use, modify, reproduce and distribute >>Bespoke.cmd
    Echo :: the Sample Application Files (and/or any modified version) in any way >>Bespoke.cmd
    Echo :: you find useful, provided that you agree that the author provides >>Bespoke.cmd
    Echo :: has no warranty, obligations or liability for any Sample Application Files. >>Bespoke.cmd
    Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
    Echo. >>Bespoke.cmd
    Echo :: ******************************************************************************** >>Bespoke.cmd
    Echo ::* Sample batch script to demonstrate the usage of Bespoke.cmd >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* File:           Bespoke.cmd >>Bespoke.cmd
    Echo ::* Date:           10/10/2013 >>Bespoke.cmd
    Echo ::* Version:        1.0.1 >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Main Function:  Allows for running of Bespoke batch with elevated rights and no future UAC 'pop-up' >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Usage:          Called and created by RunAs.cmd run from desired location >>Bespoke.cmd
    Echo ::*                 Found in the C:\Utilities folder >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Distributed under a "GNU GPL" type basis. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Revisions: >>Bespoke.cmd
    Echo ::* 1.0.0 - 09/10/2013 - Created. >>Bespoke.cmd
    Echo ::* 1.0.1 - 10/10/2013 - Modified, added ability to temp disable UAC pop-up warning. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* REFERENCES: >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Exit code (%%^ErrorLevel%%) 0 - No errors have occurred, i.e. immediate previous command ran successfully >>Bespoke.cmd
    Echo ::* Exit code (%%^ErrorLevel%%) 1 - Errors occurred, i.e. immediate previous command ran Unsuccessfully >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* MS OS version check >>Bespoke.cmd
    Echo ::* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Copying to certain folders and running certain apps require elevated perms >>Bespoke.cmd
    Echo ::* Even with 'Run As ...' perms, UAC still pops up. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* To run a script or application in the Windows Shell >>Bespoke.cmd
    Echo ::* http://ss64.com/vb/shellexecute.html >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Machines joined to a corporate Domain should have the UAC feature set from, and >>Bespoke.cmd
    Echo ::* pushed out from a DC GPO policy >>Bespoke.cmd
    Echo ::* e.g.: 'Computer Configuration - Policies - Windows Settings - Security Settings -  >>Bespoke.cmd
    Echo ::* Local Policies/Security Options - User Account Control -  >>Bespoke.cmd
    Echo ::* Policy: User Account Control: Behavior of the elevation prompt for administrators >>Bespoke.cmd
    Echo ::*         in Admin Approval Mode  Setting: Elevate without prompting >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo :: ******************************************************************************** >>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo @Echo off ^& cls>>Bespoke.cmd
    Echo color 9F>>Bespoke.cmd
    Echo Title RUN AS ADMIN>>Bespoke.cmd
    Echo Setlocal>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo Set "_OSVer=">>Bespoke.cmd
    Echo Set "_OSVer=UAC">>Bespoke.cmd
    Echo VER ^| FINDSTR /IL "5." ^>NUL>>Bespoke.cmd
    Echo IF %%^ErrorLevel%%==0 SET "_OSVer=PreUAC">>Bespoke.cmd
    Echo IF %%^_OSVer%%==PreUAC Goto:XPAdmin>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :: Check if machine part of a Domain or within a Workgroup environment >>Bespoke.cmd
    Echo Set "_DomainStat=">>Bespoke.cmd
    Echo Set "_DomainStat=%%USERDOMAIN%%">>Bespoke.cmd
    Echo If /i %%^_DomainStat%% EQU %%^computername%% (>>Bespoke.cmd
    Echo Goto:WorkgroupMember>>Bespoke.cmd
    Echo ) ELSE (>>Bespoke.cmd
    Echo Set "_DomainStat=DomMember" ^& Goto:DomainMember>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :WorkgroupMember>>Bespoke.cmd
    Echo :: Verify status of Secpol.msc 'ConsentPromptBehaviorAdmin' Reg key >>Bespoke.cmd
    Echo reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin ^| Find /i "0x0">>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo If %%^ErrorLevel%%==0 (>>Bespoke.cmd
    Echo    Goto:BespokeBuild>>Bespoke.cmd
    Echo ) Else (>>Bespoke.cmd
    Echo    Goto:DisUAC>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo :DisUAC>>Bespoke.cmd
    Echo :XPAdmin>>Bespoke.cmd
    Echo :DomainMember>>Bespoke.cmd
    Echo :: Get ADMIN Privileges, Start batch again, modify UAC ConsentPromptBehaviorAdmin reg if needed >>Bespoke.cmd
    Echo ^>nul ^2^>^&1 ^"^%%^SYSTEMROOT%%\system32\cacls.exe^"^ ^"^%%^SYSTEMROOT%%\system32\config\system^">>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo IF ^'^%%^Errorlevel%%^'^ NEQ '0' (>>Bespoke.cmd
    Echo    echo Set objShell = CreateObject^^("Shell.Application"^^) ^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    echo objShell.ShellExecute ^"^%%~s0^"^, "", "", "runas", 1 ^>^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    del ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    exit /B>>Bespoke.cmd
    Echo ) else (>>Bespoke.cmd
    Echo    pushd ^"^%%^cd%%^">>Bespoke.cmd
    Echo    cd /d ^"^%%~dp0^">>Bespoke.cmd
    Echo    @echo off>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo IF %%^_OSVer%%==PreUAC Goto:BespokeBuild>>Bespoke.cmd
    Echo IF %%^_DomainStat%%==DomMember Goto:BespokeBuild>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :BespokeBuild>>Bespoke.cmd
    Echo :: Add your script requiring elevated perm and no UAC below: >>Bespoke.cmd
    Echo.>>Bespoke.cmd

    :: PROVIDE BRIEF EXPLINATION AS TO WHAT YOUR SCRIPT WILL ACHIEVE
    Echo ::

    :: ADD THE "PAUSE" BELOW ONLY IF YOU SET TO SEE RESULTS FROM YOUR SCRIPT
    Echo Pause>>Bespoke.cmd

    Echo Goto:EOF>>Bespoke.cmd
    Echo :EOF>>Bespoke.cmd
    Echo Exit>>Bespoke.cmd

    Timeout /T 1 /NOBREAK >Nul
    :RunBatch
    call "Bespoke.cmd"
    :: Del /F /Q "Bespoke.cmd"

    :Secpol
    :: Edit out the 'Exit (rem or ::) to run & import default wins 8 security policy provided below
    Exit

    :: Check if machine part of a Domain or within a Workgroup environment
    Set "_DomainStat="
    Set _DomainStat=%USERDOMAIN%
    If /i %_DomainStat% EQU %computername% (
        Goto:WorkgroupPC
    ) ELSE (
        Echo PC Member of a Domain, Security Policy determined by GPO
        Pause
        Goto:EOF
    )

    :WorkgroupPC

    reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
    Echo.
    If %ErrorLevel%==0 (
        Echo Machine already set for UAC 'Prompt'
        Pause
        Goto:EOF
    ) else (
        Goto:EnableUAC
    )
    :EnableUAC
    IF NOT EXIST C:\Utilities\Wins8x64Def.inf (
        GOTO:CreateInf
    ) ELSE (
        Goto:RunInf
    )
    :CreateInf
    :: This will create the default '*.inf' file and import it into the 
    :: local security policy for the Wins 8 machine
    Echo [Unicode]>>Wins8x64Def.inf
    Echo Unicode=yes>>Wins8x64Def.inf
    Echo [System Access]>>Wins8x64Def.inf
    Echo MinimumPasswordAge = ^0>>Wins8x64Def.inf
    Echo MaximumPasswordAge = ^-1>>Wins8x64Def.inf
    Echo MinimumPasswordLength = ^0>>Wins8x64Def.inf
    Echo PasswordComplexity = ^0>>Wins8x64Def.inf
    Echo PasswordHistorySize = ^0>>Wins8x64Def.inf
    Echo LockoutBadCount = ^0>>Wins8x64Def.inf
    Echo RequireLogonToChangePassword = ^0>>Wins8x64Def.inf
    Echo ForceLogoffWhenHourExpire = ^0>>Wins8x64Def.inf
    Echo NewAdministratorName = ^"^Administrator^">>Wins8x64Def.inf
    Echo NewGuestName = ^"^Guest^">>Wins8x64Def.inf
    Echo ClearTextPassword = ^0>>Wins8x64Def.inf
    Echo LSAAnonymousNameLookup = ^0>>Wins8x64Def.inf
    Echo EnableAdminAccount = ^0>>Wins8x64Def.inf
    Echo EnableGuestAccount = ^0>>Wins8x64Def.inf
    Echo [Event Audit]>>Wins8x64Def.inf
    Echo AuditSystemEvents = ^0>>Wins8x64Def.inf
    Echo AuditLogonEvents = ^0>>Wins8x64Def.inf
    Echo AuditObjectAccess = ^0>>Wins8x64Def.inf
    Echo AuditPrivilegeUse = ^0>>Wins8x64Def.inf
    Echo AuditPolicyChange = ^0>>Wins8x64Def.inf
    Echo AuditAccountManage = ^0>>Wins8x64Def.inf
    Echo AuditProcessTracking = ^0>>Wins8x64Def.inf
    Echo AuditDSAccess = ^0>>Wins8x64Def.inf
    Echo AuditAccountLogon = ^0>>Wins8x64Def.inf
    Echo [Registry Values]>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\CachedLogonsCount=1,"10">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceUnlockLogon=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning=4,5>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption=1,"0">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin=4,5>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorUser=4,3>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableCAD=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableInstallerDetection=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableSecureUIAPaths=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableVirtualization=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeCaption=1,"">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeText=7,>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\PromptOnSecureDesktop=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ScForceOption=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ShutdownWithoutLogon=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\UndockWithoutLogon=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ValidateAdminCodeSignatures=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\AuthenticodeEnabled=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\AuditBaseObjects=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\CrashOnAuditFail=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\DisableDomainCreds=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\FullPrivilegeAuditing=3,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinClientSec=4,536870912>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinServerSec=4,536870912>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\NoLMHash=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymous=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers\AddPrinterDrivers=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactPaths\Machine=7,System\CurrentControlSet\Control\ProductOptions,System\CurrentControlSet\Control\Server Applications,Software\Microsoft\Windows NT\CurrentVersion>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedPaths\Machine=7,System\CurrentControlSet\Control\Print\Printers,System\CurrentControlSet\Services\Eventlog,Software\Microsoft\OLAP Server,Software\Microsoft\Windows NT\CurrentVersion\Print,Software\Microsoft\Windows NT\CurrentVersion\Windows,System\CurrentControlSet\Control\ContentIndex,System\CurrentControlSet\Control\Terminal Server,System\CurrentControlSet\Control\Terminal Server\UserConfig,System\CurrentControlSet\Control\Terminal Server\DefaultUserConfiguration,Software\Microsoft\Windows NT\CurrentVersion\Perflib,System\CurrentControlSet\Services\SysmonLog>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Kernel\ObCaseInsensitive=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management\ClearPageFileAtShutdown=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\ProtectionMode=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\optional=7,Posix>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\AutoDisconnect=4,15>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableForcedLogOff=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionPipes=7,>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RestrictNullSessAccess=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnablePlainTextPassword=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnableSecuritySignature=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LDAP\LDAPClientIntegrity=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\MaximumPasswordAge=4,30>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireSignOrSeal=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireStrongKey=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SealSecureChannel=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SignSecureChannel=4,1>>Wins8x64Def.inf
    Echo [Privilege Rights]>>Wins8x64Def.inf
    Echo SeNetworkLogonRight = *S-1-1-0,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeBackupPrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeChangeNotifyPrivilege = *S-1-1-0,*S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551,*S-1-5-90-^0>>Wins8x64Def.inf
    Echo SeSystemtimePrivilege = *S-1-5-19,*S-1-5-32-544>>Wins8x64Def.inf
    Echo SeCreatePagefilePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeDebugPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeRemoteShutdownPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeAuditPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
    Echo SeIncreaseQuotaPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544>>Wins8x64Def.inf
    Echo SeIncreaseBasePriorityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeLoadDriverPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeBatchLogonRight = *S-1-5-32-544,*S-1-5-32-551,*S-1-5-32-559>>Wins8x64Def.inf
    Echo SeServiceLogonRight = *S-1-5-80-0,*S-1-5-83-^0>>Wins8x64Def.inf
    Echo SeInteractiveLogonRight = Guest,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeSecurityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeSystemEnvironmentPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeProfileSingleProcessPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeSystemProfilePrivilege = *S-1-5-32-544,*S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420>>Wins8x64Def.inf
    Echo SeAssignPrimaryTokenPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
    Echo SeRestorePrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeShutdownPrivilege = *S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeTakeOwnershipPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeDenyNetworkLogonRight = Guest>>Wins8x64Def.inf
    Echo SeDenyInteractiveLogonRight = Guest>>Wins8x64Def.inf
    Echo SeUndockPrivilege = *S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
    Echo SeManageVolumePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeRemoteInteractiveLogonRight = *S-1-5-32-544,*S-1-5-32-555>>Wins8x64Def.inf
    Echo SeImpersonatePrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
    Echo SeCreateGlobalPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
    Echo SeIncreaseWorkingSetPrivilege = *S-1-5-32-545,*S-1-5-90-^0>>Wins8x64Def.inf
    Echo SeTimeZonePrivilege = *S-1-5-19,*S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
    Echo SeCreateSymbolicLinkPrivilege = *S-1-5-32-544,*S-1-5-83-^0>>Wins8x64Def.inf
    Echo [Version]>>Wins8x64Def.inf
    Echo signature="$CHICAGO$">>Wins8x64Def.inf
    Echo Revision=1>>Wins8x64Def.inf

    :RunInf
    :: Import 'Wins8x64Def.inf' with ADMIN Privileges, to modify UAC ConsentPromptBehaviorAdmin reg
    >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%%\system32\config\system"
    IF '%Errorlevel%' NEQ '0' (
        echo Set objShell = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo objShell.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
       "%temp%%\getadmin.vbs"
        del "%temp%\getadmin.vbs"
        exit /B
        Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
        Goto:CheckUAC
    ) else (
        Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
        @echo off
    )
    :CheckUAC
    reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
    Echo.
    If %ErrorLevel%==0 (
        Echo ConsentPromptBehaviorAdmin set to 'Prompt'
        Pause
        Del /Q C:\Utilities\Wins8x64Def.inf
        Goto:EOF
    ) else (
        Echo ConsentPromptBehaviorAdmin NOT set to default
        Pause
    )
    ENDLOCAL
    :EOF
    Exit

Domain PC's should be governed as much as possible by GPO sets. Workgroup/Standalone machines can be governed by this script.

Remember, a UAC prompt will pop-up at least once with a BYOD workgroup PC (as soon as the first elevating to 'Admin perms' is required), but as the local security policy is modified for admin use from this point on, the pop-ups will disappear.

A Domain PC should have the GPO "ConsentPromptBehaviorAdmin" policy set within your 'already' created "Lock-down" policy - as explained in the script 'REFERENCES' section.

Again, run the secedit.exe import of the default '.inf' file if you are stuck on the whole "To UAC or Not to UAC" debate :-).

btw: @boileau Do check your failure on the:

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

By running only "%SYSTEMROOT%\system32\cacls.exe" or "%SYSTEMROOT%\system32\config\system" or both from the command prompt - elevated or not, check the result across the board.

Capacitor answered 13/10, 2013 at 17:27 Comment(0)
H
-2

Another way to do this.

REM    # # # #      CHECKING OR IS STARTED AS ADMINISTRATOR     # # # # #

FSUTIL | findstr /I "volume" > nul&if not errorlevel 1  goto Administrator_OK

cls
echo *******************************************************
echo ***    R U N    A S    A D M I N I S T R A T O R    ***
echo *******************************************************
echo.
echo.
echo Call up just as the Administrator. Abbreviation can be done to the script and set:
echo.
echo      Shortcut ^> Advanced ^> Run as Administrator
echo.
echo.
echo Alternatively, a single run "Run as Administrator"
echo or in the Schedule tasks with highest privileges
pause > nul
goto:eof
:Administrator_OK

REM Some next lines code ...
Hyetography answered 7/4, 2015 at 22:52 Comment(2)
What is that link supposed to be? Flagged as spam because of the link.Everett
Check this answer for a code that checks and prompts automatically: https://mcmap.net/q/13751/-how-to-request-administrator-access-inside-a-batch-fileDortheydorthy

© 2022 - 2024 — McMap. All rights reserved.