Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

18
sign up log in tour help stack overflow careers Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free. Batch script: how to check for admin rights 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. windows batch-file cmd admin edited Jan 14 '13 at 8:24 a_horse_with_no_name 136k 15 142 209 asked Oct 29 '10 at 12:35 flacs 731 2 7 15 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 [ [1]: stackoverflow.com/questions/4051883/… stackoverflow.com/questions/4051883/… Amr Ali Nov 23 '14 at 0:02 18 Answers Issues / 's solution works fine for everything except Windows 8. Running on Windows 8 results in: blak3r Rushyo AT 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. 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. rationallyparanoid.com Eventually, I did find one - . A , clean, universal solution that doesn't involve: NET SESSION true the creation of or interaction with data in secure locations analyzing data returned from loops FOR searching strings for "Administrator" using (Windows 8 incompatible) or (Windows XP incompatible). AT WHOAMI 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

description

Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Transcript of Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Page 1: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

sign up log in tour help stack overflow careers

Take the 2-minute tour timesStack Overflow is a question and answer site for professional and enthusiast programmers Its 100 free

Batch script how to check for admin rights

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 Ive seen are crude hack jobs or use

external programs Well actually I dont care if it is a hack job as long as it works on Windows XP and newer

windows batch-file cmd admin

edited Jan 14 13 at 824

a_horse_with_no_name

136k 15 142 209

asked Oct 29 10 at 1235

flacs

731 2 7 15

ndash

after you can change the right [How to request Administrator access inside a batch file][1] [1]stackoverflowcomquestions1894967hellip Alban Apr 17 13 at 1522

ndash Look here How can I auto-elevate my script or check for admin rights Matt Dec 3 13 at 825

ndash [ [1] stackoverflowcomquestions4051883hellip stackoverflowcomquestions4051883hellip Amr Ali Nov 2314 at 002

18 Answers

Issues

s solution works fine for everything except Windows 8 Running on Windows

8 results in

blak3r Rushyo AT

The AT command has been deprecated Please use schtasksexe 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

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

rationallyparanoidcom

Eventually I did find one - A clean universal solution that doesnt involveNET SESSION true

the creation of or interaction with data in secure locations

analyzing data returned from loopsFOR

searching strings for Administrator

using (Windows 8 incompatible) or (Windows XP incompatible)AT WHOAMI

Each of which have their own security usability and portability issues

Testing

Ive 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

(see screenshot 2)

Implementation Usage

So to use this solution simply do something like this

echo offgoto check_Permissions

check_Permissions echo Administrative permissions required Detecting permissions

net session gtnul 2gtamp1 if errorLevel == 0 ( echo Success Administrative permissions confirmed ) else ( echo Failure Current permissions inadequate )

pause gtnul

Available here if youre lazy

httpsdldropboxcomu27573003DistributionBinariescheck_Permissionsbat

Explanation

is a standard command used to NET SESSION manage server computer connections Used

without parameters [it] displays information about all sessions with the local computer

So heres the basic process of my given implementation

1 echo off

Disable displaying of commands

2 goto check_Permissions

Jump to the code blockcheck_Permissions

3 net session gtnul 2gtamp1

Run command

Hide visual output of command by

1 Redirecting the standard output (numeric handle 1 ) stream to STDOUT nul

2 Redirecting the standard error output stream (numeric handle 2 ) to the

same destination as numeric handle 1

STDERR

4 if errorLevel == 0

If the value of the exit code ( ) then this means that

and therefore the immediate previous command ran

errorLevel is 0 no errors have

occurred successfully

5 else

If the value of the exit code ( ) then this means that

and therefore the immediate previous command ran

errorLevel is not 0 errors have

occurred unsuccessfully

6 The code between the respective parenthesis will be executed depending on which criteria is

met

Screenshots

Windows 8 AT errorLevel

on Windows XP x86 - Windows 8 x64NET SESSION

Thank you Tilka for changing your accepted answer to mine )

edited Apr 5 13 at 821 community wiki

12 revs

Ben Hooper

5 ndash +1 Awesome job Good research Your post should deserves to be new accepted answer blak3r Aug 2812 at 512

1 ndash good job buddythanks +1 Sandy Jan 11 13 at 1319

5

ndash

This solution normally works great but if the Server (LanmanServer) service is stopped the error code forServer service has not been started is the same error code that you get for Access is denied resulting ina false negative In other words there are cases where you can run this check with administrative privilegesand it will return the same error as it would without those privileges Lectrode Nov 16 13 at 351

2 ndash

Lectrode Ive posted an alternative solution which doesnt have the same issuestackoverflowcomquestions4051883hellip and31415 Jan 22 14 at 2304

2

ndash

This code returns a false positive (at least on Windows 7) if the user is a Power User A Power User canalso elevate and then run successfully (ERRORLEVEL = 0) - but they dont actually have

admin rights Using (see answer by below) doesnt have this problem

net session

openfiles Lucretius E M Jan 14

at 1732

Anders solution worked for me but I wasnt sure how to invert it to get the opposite (when you

werent an admin)

Heres 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 Administratorhas elevated

privileges

NET SESSION gtnul 2gtamp1IF 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 isnt it pauses and then quits]-------echo OFFNET SESSION gtnul 2gtamp1IF 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 youre 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 --gt Win8 (including 3264 bit versions)

EDIT 8282012 Updated to support Windows 8 BenHooper pointed this out in his

answer below Please upvote his answer

edited Dec 28 12 at 2356 answered Jan 24 12 at 2247

blak3r

6318 6 43 69

ndash

doesnt work on Windows 8 but Ive found a better solution Ive posted it as an answer here actually

(or you could just scroll down whatever)

AT

stackoverflowcomquestions4051883hellip mythofechelon Aug 1612 at 2127

1 ndash

I wonder if two lines of if errorLevel == EQU on first code-block is a TYPO please correctUjjwal Singh Sep 4 12 at 813

ndash UjjwalSingh It sure was Thanks for catching Ive updated it blak3r Sep 4 12 at 2305

ndash

Might want to replace the Rushyo posted this solution here with your comment about me now that youreusing my solution ) mythofechelon Jan 16 13 at 014

ndash

Doesnt work for the Domain Admins Group added to Administrators Group in the local machine and loginwith the domain Admin user MCRohith Jan 17 13 at 1000

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystemampamp( echo admin)

answered Oct 29 10 at 1851

Anders

406k 5 36 77

1 ndash

It seems that in some cases the test always failed even after being elevated In my case when the scriptwas called by my application boileau Feb 13 12 at 1601

More issues

As pointed out by Lectrode if you try to run the command while the Server

service is stopped you receive the following error message

net session

The Server service is not started

More help is available by typing NET HELPMSG 2114

In this case the variable will be set to errorLevel 2

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

Looking for an alternative

Something that

can be run out of the box on Windows XP and later (32 and 64 bit)

doesnt touch the registry or any system filefolder

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 folder trying to get some ideas After trials and errors

this is the (pun intended) approach Ive come up with

CWindowsSystem32

dirty

fsutil dirty query systemdrive gtnul

The command requires admin rights to run and will fail otherwise

is an which returns the drive letter where the operating system is installed

The output is redirected to thus ignored The variable will be set to only

upon successful execution

fsutil dirty systemdrive

environment variable

nul errorlevel 0

Here is what the documentation says

Fsutil dirty

Queries or sets a volumes dirty bit When a volumes dirty bit is set automatically

checks the volume for errors the next time the computer is restarted

autochk

Syntax

fsutil dirty query | set ltVolumePathgt

Parameters

query Queries the specified volumes dirty bitset Sets the specified volumes dirty bitltVolumePathgt Specifies the drive name followed by a colon or GUID

Remarks

A volumes 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 runs to verify the file system integrity

and to attempt to fix any issues with the volume

chkdsk

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 its worth adding that Windows 2000

and Windows PE (Preinstalled Environment) dont come with so we have to resort

to something else

fsutilexe

During my previous tests I noticed that running the command without any parameters would

either result in

sfc

an error if you didnt have enough privileges

a list of the available parameters and their usage

That is no parameters The idea is that we can parse the output and check if we got

anything but an error

no party

sfc 2gtamp1 | find i SCANNOW gtnul

The error output is first redirected to the standard output which is then piped to the

command At this point we have to look for the parameter that is

since Windows 2000 The search is case insensitive and the output is

discarded by redirecting it to

find

only supported in all Windows

version SCANNOW

nul

Heres 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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 2: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Windows Vista x64

Windows 7 x86

Windows 7 x64

Windows 8 x86

Windows 8 x64

(see screenshot 2)

Implementation Usage

So to use this solution simply do something like this

echo offgoto check_Permissions

check_Permissions echo Administrative permissions required Detecting permissions

net session gtnul 2gtamp1 if errorLevel == 0 ( echo Success Administrative permissions confirmed ) else ( echo Failure Current permissions inadequate )

pause gtnul

Available here if youre lazy

httpsdldropboxcomu27573003DistributionBinariescheck_Permissionsbat

Explanation

is a standard command used to NET SESSION manage server computer connections Used

without parameters [it] displays information about all sessions with the local computer

So heres the basic process of my given implementation

1 echo off

Disable displaying of commands

2 goto check_Permissions

Jump to the code blockcheck_Permissions

3 net session gtnul 2gtamp1

Run command

Hide visual output of command by

1 Redirecting the standard output (numeric handle 1 ) stream to STDOUT nul

2 Redirecting the standard error output stream (numeric handle 2 ) to the

same destination as numeric handle 1

STDERR

4 if errorLevel == 0

If the value of the exit code ( ) then this means that

and therefore the immediate previous command ran

errorLevel is 0 no errors have

occurred successfully

5 else

If the value of the exit code ( ) then this means that

and therefore the immediate previous command ran

errorLevel is not 0 errors have

occurred unsuccessfully

6 The code between the respective parenthesis will be executed depending on which criteria is

met

Screenshots

Windows 8 AT errorLevel

on Windows XP x86 - Windows 8 x64NET SESSION

Thank you Tilka for changing your accepted answer to mine )

edited Apr 5 13 at 821 community wiki

12 revs

Ben Hooper

5 ndash +1 Awesome job Good research Your post should deserves to be new accepted answer blak3r Aug 2812 at 512

1 ndash good job buddythanks +1 Sandy Jan 11 13 at 1319

5

ndash

This solution normally works great but if the Server (LanmanServer) service is stopped the error code forServer service has not been started is the same error code that you get for Access is denied resulting ina false negative In other words there are cases where you can run this check with administrative privilegesand it will return the same error as it would without those privileges Lectrode Nov 16 13 at 351

2 ndash

Lectrode Ive posted an alternative solution which doesnt have the same issuestackoverflowcomquestions4051883hellip and31415 Jan 22 14 at 2304

2

ndash

This code returns a false positive (at least on Windows 7) if the user is a Power User A Power User canalso elevate and then run successfully (ERRORLEVEL = 0) - but they dont actually have

admin rights Using (see answer by below) doesnt have this problem

net session

openfiles Lucretius E M Jan 14

at 1732

Anders solution worked for me but I wasnt sure how to invert it to get the opposite (when you

werent an admin)

Heres 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 Administratorhas elevated

privileges

NET SESSION gtnul 2gtamp1IF 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 isnt it pauses and then quits]-------echo OFFNET SESSION gtnul 2gtamp1IF 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 youre 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 --gt Win8 (including 3264 bit versions)

EDIT 8282012 Updated to support Windows 8 BenHooper pointed this out in his

answer below Please upvote his answer

edited Dec 28 12 at 2356 answered Jan 24 12 at 2247

blak3r

6318 6 43 69

ndash

doesnt work on Windows 8 but Ive found a better solution Ive posted it as an answer here actually

(or you could just scroll down whatever)

AT

stackoverflowcomquestions4051883hellip mythofechelon Aug 1612 at 2127

1 ndash

I wonder if two lines of if errorLevel == EQU on first code-block is a TYPO please correctUjjwal Singh Sep 4 12 at 813

ndash UjjwalSingh It sure was Thanks for catching Ive updated it blak3r Sep 4 12 at 2305

ndash

Might want to replace the Rushyo posted this solution here with your comment about me now that youreusing my solution ) mythofechelon Jan 16 13 at 014

ndash

Doesnt work for the Domain Admins Group added to Administrators Group in the local machine and loginwith the domain Admin user MCRohith Jan 17 13 at 1000

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystemampamp( echo admin)

answered Oct 29 10 at 1851

Anders

406k 5 36 77

1 ndash

It seems that in some cases the test always failed even after being elevated In my case when the scriptwas called by my application boileau Feb 13 12 at 1601

More issues

As pointed out by Lectrode if you try to run the command while the Server

service is stopped you receive the following error message

net session

The Server service is not started

More help is available by typing NET HELPMSG 2114

In this case the variable will be set to errorLevel 2

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

Looking for an alternative

Something that

can be run out of the box on Windows XP and later (32 and 64 bit)

doesnt touch the registry or any system filefolder

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 folder trying to get some ideas After trials and errors

this is the (pun intended) approach Ive come up with

CWindowsSystem32

dirty

fsutil dirty query systemdrive gtnul

The command requires admin rights to run and will fail otherwise

is an which returns the drive letter where the operating system is installed

The output is redirected to thus ignored The variable will be set to only

upon successful execution

fsutil dirty systemdrive

environment variable

nul errorlevel 0

Here is what the documentation says

Fsutil dirty

Queries or sets a volumes dirty bit When a volumes dirty bit is set automatically

checks the volume for errors the next time the computer is restarted

autochk

Syntax

fsutil dirty query | set ltVolumePathgt

Parameters

query Queries the specified volumes dirty bitset Sets the specified volumes dirty bitltVolumePathgt Specifies the drive name followed by a colon or GUID

Remarks

A volumes 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 runs to verify the file system integrity

and to attempt to fix any issues with the volume

chkdsk

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 its worth adding that Windows 2000

and Windows PE (Preinstalled Environment) dont come with so we have to resort

to something else

fsutilexe

During my previous tests I noticed that running the command without any parameters would

either result in

sfc

an error if you didnt have enough privileges

a list of the available parameters and their usage

That is no parameters The idea is that we can parse the output and check if we got

anything but an error

no party

sfc 2gtamp1 | find i SCANNOW gtnul

The error output is first redirected to the standard output which is then piped to the

command At this point we have to look for the parameter that is

since Windows 2000 The search is case insensitive and the output is

discarded by redirecting it to

find

only supported in all Windows

version SCANNOW

nul

Heres 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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 3: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

on Windows XP x86 - Windows 8 x64NET SESSION

Thank you Tilka for changing your accepted answer to mine )

edited Apr 5 13 at 821 community wiki

12 revs

Ben Hooper

5 ndash +1 Awesome job Good research Your post should deserves to be new accepted answer blak3r Aug 2812 at 512

1 ndash good job buddythanks +1 Sandy Jan 11 13 at 1319

5

ndash

This solution normally works great but if the Server (LanmanServer) service is stopped the error code forServer service has not been started is the same error code that you get for Access is denied resulting ina false negative In other words there are cases where you can run this check with administrative privilegesand it will return the same error as it would without those privileges Lectrode Nov 16 13 at 351

2 ndash

Lectrode Ive posted an alternative solution which doesnt have the same issuestackoverflowcomquestions4051883hellip and31415 Jan 22 14 at 2304

2

ndash

This code returns a false positive (at least on Windows 7) if the user is a Power User A Power User canalso elevate and then run successfully (ERRORLEVEL = 0) - but they dont actually have

admin rights Using (see answer by below) doesnt have this problem

net session

openfiles Lucretius E M Jan 14

at 1732

Anders solution worked for me but I wasnt sure how to invert it to get the opposite (when you

werent an admin)

Heres 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 Administratorhas elevated

privileges

NET SESSION gtnul 2gtamp1IF 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 isnt it pauses and then quits]-------echo OFFNET SESSION gtnul 2gtamp1IF 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 youre 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 --gt Win8 (including 3264 bit versions)

EDIT 8282012 Updated to support Windows 8 BenHooper pointed this out in his

answer below Please upvote his answer

edited Dec 28 12 at 2356 answered Jan 24 12 at 2247

blak3r

6318 6 43 69

ndash

doesnt work on Windows 8 but Ive found a better solution Ive posted it as an answer here actually

(or you could just scroll down whatever)

AT

stackoverflowcomquestions4051883hellip mythofechelon Aug 1612 at 2127

1 ndash

I wonder if two lines of if errorLevel == EQU on first code-block is a TYPO please correctUjjwal Singh Sep 4 12 at 813

ndash UjjwalSingh It sure was Thanks for catching Ive updated it blak3r Sep 4 12 at 2305

ndash

Might want to replace the Rushyo posted this solution here with your comment about me now that youreusing my solution ) mythofechelon Jan 16 13 at 014

ndash

Doesnt work for the Domain Admins Group added to Administrators Group in the local machine and loginwith the domain Admin user MCRohith Jan 17 13 at 1000

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystemampamp( echo admin)

answered Oct 29 10 at 1851

Anders

406k 5 36 77

1 ndash

It seems that in some cases the test always failed even after being elevated In my case when the scriptwas called by my application boileau Feb 13 12 at 1601

More issues

As pointed out by Lectrode if you try to run the command while the Server

service is stopped you receive the following error message

net session

The Server service is not started

More help is available by typing NET HELPMSG 2114

In this case the variable will be set to errorLevel 2

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

Looking for an alternative

Something that

can be run out of the box on Windows XP and later (32 and 64 bit)

doesnt touch the registry or any system filefolder

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 folder trying to get some ideas After trials and errors

this is the (pun intended) approach Ive come up with

CWindowsSystem32

dirty

fsutil dirty query systemdrive gtnul

The command requires admin rights to run and will fail otherwise

is an which returns the drive letter where the operating system is installed

The output is redirected to thus ignored The variable will be set to only

upon successful execution

fsutil dirty systemdrive

environment variable

nul errorlevel 0

Here is what the documentation says

Fsutil dirty

Queries or sets a volumes dirty bit When a volumes dirty bit is set automatically

checks the volume for errors the next time the computer is restarted

autochk

Syntax

fsutil dirty query | set ltVolumePathgt

Parameters

query Queries the specified volumes dirty bitset Sets the specified volumes dirty bitltVolumePathgt Specifies the drive name followed by a colon or GUID

Remarks

A volumes 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 runs to verify the file system integrity

and to attempt to fix any issues with the volume

chkdsk

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 its worth adding that Windows 2000

and Windows PE (Preinstalled Environment) dont come with so we have to resort

to something else

fsutilexe

During my previous tests I noticed that running the command without any parameters would

either result in

sfc

an error if you didnt have enough privileges

a list of the available parameters and their usage

That is no parameters The idea is that we can parse the output and check if we got

anything but an error

no party

sfc 2gtamp1 | find i SCANNOW gtnul

The error output is first redirected to the standard output which is then piped to the

command At this point we have to look for the parameter that is

since Windows 2000 The search is case insensitive and the output is

discarded by redirecting it to

find

only supported in all Windows

version SCANNOW

nul

Heres 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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 4: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

rem ----[ This code block detects if the script is being running with admin PRIVILEGES If it isnt it pauses and then quits]-------echo OFFNET SESSION gtnul 2gtamp1IF 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 youre 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 --gt Win8 (including 3264 bit versions)

EDIT 8282012 Updated to support Windows 8 BenHooper pointed this out in his

answer below Please upvote his answer

edited Dec 28 12 at 2356 answered Jan 24 12 at 2247

blak3r

6318 6 43 69

ndash

doesnt work on Windows 8 but Ive found a better solution Ive posted it as an answer here actually

(or you could just scroll down whatever)

AT

stackoverflowcomquestions4051883hellip mythofechelon Aug 1612 at 2127

1 ndash

I wonder if two lines of if errorLevel == EQU on first code-block is a TYPO please correctUjjwal Singh Sep 4 12 at 813

ndash UjjwalSingh It sure was Thanks for catching Ive updated it blak3r Sep 4 12 at 2305

ndash

Might want to replace the Rushyo posted this solution here with your comment about me now that youreusing my solution ) mythofechelon Jan 16 13 at 014

ndash

Doesnt work for the Domain Admins Group added to Administrators Group in the local machine and loginwith the domain Admin user MCRohith Jan 17 13 at 1000

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystemampamp( echo admin)

answered Oct 29 10 at 1851

Anders

406k 5 36 77

1 ndash

It seems that in some cases the test always failed even after being elevated In my case when the scriptwas called by my application boileau Feb 13 12 at 1601

More issues

As pointed out by Lectrode if you try to run the command while the Server

service is stopped you receive the following error message

net session

The Server service is not started

More help is available by typing NET HELPMSG 2114

In this case the variable will be set to errorLevel 2

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

Looking for an alternative

Something that

can be run out of the box on Windows XP and later (32 and 64 bit)

doesnt touch the registry or any system filefolder

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 folder trying to get some ideas After trials and errors

this is the (pun intended) approach Ive come up with

CWindowsSystem32

dirty

fsutil dirty query systemdrive gtnul

The command requires admin rights to run and will fail otherwise

is an which returns the drive letter where the operating system is installed

The output is redirected to thus ignored The variable will be set to only

upon successful execution

fsutil dirty systemdrive

environment variable

nul errorlevel 0

Here is what the documentation says

Fsutil dirty

Queries or sets a volumes dirty bit When a volumes dirty bit is set automatically

checks the volume for errors the next time the computer is restarted

autochk

Syntax

fsutil dirty query | set ltVolumePathgt

Parameters

query Queries the specified volumes dirty bitset Sets the specified volumes dirty bitltVolumePathgt Specifies the drive name followed by a colon or GUID

Remarks

A volumes 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 runs to verify the file system integrity

and to attempt to fix any issues with the volume

chkdsk

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 its worth adding that Windows 2000

and Windows PE (Preinstalled Environment) dont come with so we have to resort

to something else

fsutilexe

During my previous tests I noticed that running the command without any parameters would

either result in

sfc

an error if you didnt have enough privileges

a list of the available parameters and their usage

That is no parameters The idea is that we can parse the output and check if we got

anything but an error

no party

sfc 2gtamp1 | find i SCANNOW gtnul

The error output is first redirected to the standard output which is then piped to the

command At this point we have to look for the parameter that is

since Windows 2000 The search is case insensitive and the output is

discarded by redirecting it to

find

only supported in all Windows

version SCANNOW

nul

Heres 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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 5: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

doesnt touch the registry or any system filefolder

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 folder trying to get some ideas After trials and errors

this is the (pun intended) approach Ive come up with

CWindowsSystem32

dirty

fsutil dirty query systemdrive gtnul

The command requires admin rights to run and will fail otherwise

is an which returns the drive letter where the operating system is installed

The output is redirected to thus ignored The variable will be set to only

upon successful execution

fsutil dirty systemdrive

environment variable

nul errorlevel 0

Here is what the documentation says

Fsutil dirty

Queries or sets a volumes dirty bit When a volumes dirty bit is set automatically

checks the volume for errors the next time the computer is restarted

autochk

Syntax

fsutil dirty query | set ltVolumePathgt

Parameters

query Queries the specified volumes dirty bitset Sets the specified volumes dirty bitltVolumePathgt Specifies the drive name followed by a colon or GUID

Remarks

A volumes 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 runs to verify the file system integrity

and to attempt to fix any issues with the volume

chkdsk

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 its worth adding that Windows 2000

and Windows PE (Preinstalled Environment) dont come with so we have to resort

to something else

fsutilexe

During my previous tests I noticed that running the command without any parameters would

either result in

sfc

an error if you didnt have enough privileges

a list of the available parameters and their usage

That is no parameters The idea is that we can parse the output and check if we got

anything but an error

no party

sfc 2gtamp1 | find i SCANNOW gtnul

The error output is first redirected to the standard output which is then piped to the

command At this point we have to look for the parameter that is

since Windows 2000 The search is case insensitive and the output is

discarded by redirecting it to

find

only supported in all Windows

version SCANNOW

nul

Heres 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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 6: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

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 sfcexe

Sample Usage

Here are some paste-and-run examples

Windows XP and later

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminfsutil dirty query systemdrive gtnulexit b

Windows 2000 Windows PE

echo off

call isAdminif errorlevel == 0 (echo Running with admin rights) else (echo Error Access denied)

pause gtnulexit b

isAdminsfc 2gtamp1 | find i SCANNOW gtnulexit b

Applies to

Windows 2000

Windows XP

Windows Vista

Windows 7

Windows 8

Windows 81

---

Windows PE

edited Jan 22 14 at 2311 answered Jan 22 14 at 2255

and31415

225 3 6

ndash

+1 Excellent solutions The SFC solution in particular seems to be a reliable check for all of the operatingsystems in question If I come across any issues using either of these I will report them here LectrodeJan 23 14 at 353

ndash

For anyone looking to use the check for all systems you need to get a bit creative For some reason

starting with Windows 8 outputs single characters only In order to successfully parse the output you

need to do the following

(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

SFC

SFC

setlocal enabledelayedexpansion for f tokens= delims= s in

(sfc 2gtamp1|MORE) do set output=outputs echo output|findstr I

Cscannowgtnul 2gtamp1

Lectrode Jan 23 14 at 846

ndash

Great work and31415 I havent personally tested your solution yet but from what I can see it

seems a lot more flexible than my solution Although not quite as elegant maybe ) Im glad to see thatbetween us were getting an excellent easy and flexible admin-detection solution pinned down )

fsutil

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 7: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

mythofechelon Jan 23 14 at 1032

ndash

When running FSUTIL you can leave out the drive letter and just run when

elevated this returns some help text and errorlevel=0

fsutil dirty query gtnul

ss64 Apr 10 at 1707

alternative solution

echo offpushd SystemRootopenfilesexe 1gtnul 2gtamp1if not errorlevel equ 0 ( Echo here you are not administrator) else ( Echo here you are administrator)popdPause

edited Jun 17 14 at 1843 answered Jun 17 14 at 1743

Lucretius

71 1 2

2 ndash Could you add an explanation to your answer bjb568 Jun 17 14 at 1824

ndash corrected more detail Lucretius Jun 17 14 at 1844

1 ndash

While this code might answer the question you should add some explanation on why it does soPlasmaHH Jun 17 14 at 2001

1 ndash

Yes This works correctly even when the user is a Power User (unlike net session) There is no need forthe pushdpopd though Just running and checking ERRORLEVEL is enoughopenfiles E M Jan 14

at 1729

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)

Not only check but GETTING admin rights automatically

aka Automatic UAC for Win 7881 ff

With this trick you donacutet 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 needsprovides UAC so it behaves correct eg for Win 2000XP until Win 81-

tested

echo offREM Quick test for Windows generation UAC aware or not all OS before NT4 ignored

for simplicitySET NewOSWith_UAC=YESVER | FINDSTR IL 5 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NOVER | FINDSTR IL 4 gt NULIF ERRORLEVEL == 0 SET NewOSWith_UAC=NO

REM Test if AdminCALL NET SESSION gtnul 2gtamp1IF NOT ERRORLEVEL == 0 (

if i NewOSWith_UAC==YES ( rem Start batch again with UAC echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbs tempgetadminvbs del tempgetadminvbs 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

dont 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 1621 answered Feb 6 13 at 1239

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 8: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Philm

1107 6 11

The following tries to create a file in the Windows directory If it suceeds it will remove it

copy by NUL WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1if errorlevel 1 gotononadmindel WINDIR06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 gtNUL 2gtamp1adminrem here you are administratorgotoeofnonadminrem here you are not administratorgotoeof

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

edited Jan 14 13 at 800 answered Oct 29 10 at 1249

Benoit

406k 11 107 168

ndash

+1 because the accepted answer caused infinitely many command windows to be opened when the scriptwas called from my application boileau Feb 13 12 at 1558

ndash +1 for speed (this is a lot faster) orlp Jan 13 13 at 1853

I have two ways of checking for privileged access both are pretty reliable and very portable

across almost every windows version

Try to create a folder inside the Windows folder

set guid=randomrandom-random-random-random-randomrandomrandom

mkdir WINDIRguidgtnul 2gtamp1rmdir WINDIRguidgtnul 2gtamp1

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

I think this is very reliable because this commands are there since forever and as Dan said

net session can be disabled

Try to write to Windows registry

REG ADD HKLM Fgtnul 2gtamp1

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

If you try to create a key on using default permissions youll get

and the ERRORLEVEL == 1 but if you run as Admin it will print

and ERRORLEVEL == 0 Since the key already exists it have no effect

on the registry This is probably the fastest way and the is there for a long time however

this behavior or the REG command may change in the future And its not avaliable on pre NT

HKEY_LOCAL_MACHINE

Access Denied command

executed successfully

REG

Full script example

On my scripts I usually use in this way

echo offmain echo echo Clear Temp Files script echo

call requirePrivilegies

rem Do something that require privilegies

del temp

pausegtnul

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 9: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

goto eof

requirePrivilegies set guid=randomrandom-random-random-random-randomrandomrandom mkdir WINDIRguidgtnul 2gtamp1 rmdir WINDIRguidgtnul 2gtamp1 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 pausegtnul exit )goto eof

edited Sep 8 13 at 320 answered Apr 27 13 at 457

Vitimus

4791 2 29 52

Some servers disable services that the command net session requires This results in the

admin check always saying you dont have admin rights when you may have

edited Mar 14 13 at 737 answered Mar 14 13 at 543

Dan

21 2

one more way

fltmc gtnul 2gtamp1 ampamp ( echo has admin permissions) || ( echo has NOT admin permissions)

command is available on every windows system since XP so this should be

pretty portable

fltmc

answered Feb 1 at 2241

npocmaka

184k 5 24 49

whoami groups | find S-1-16-12288 gt nulif not errorlevel 1 ( echo connected as admin)

answered Jan 15 12 at 1856

Totonga

2404 1 11 23

2 ndash

Problem here is that you check whether the user has admin rights But the batch script could run withoutadmin rights tanascius Mar 23 12 at 1030

2 ndash Plus isnt supported in Windows XPwhoami mythofechelon Aug 16 12 at 1514

ndash

Also whoami groups has an edge case where you get the wrong information Seestackoverflowcomquestions4051883hellip zumalifeguard Jun 18 at 1725

Heres 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 hadnt been createdloadedor ready in time to

apply a remove andor Pin taskbar and Start Menu items vbscript + add some local files

eg The proposed default-user profile environment requires a URL (lnk) shortcut placed

within the ProgramDataMicrosoftWindowsStart MenuProgramsMyNewOWAurl and

the CUsersPublicDesktopMyNewOWAurl 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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 10: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

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 (andor 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 RunAscmd File RunAscmd Date 12102013 Version 102 Main Function Verifies status of bespoke Scripts ability to Run As - Admin elevated privileges and without UAC prompt Usage Run RunAscmd from desired location Bespokecmd will be created and called from CUtilities location Choose whether to delete the script after its run by removing out-comment () before the Del q Bespokecmd command Distributed under a GNU GPL type basis Revisions 100 - 08102013 - Created 101 - 09102013 - Include new path creation 102 - 12102013 - Modifyshorten UAC disable process for Admins REFERENCES Sample inf secpolmsc export from Wins 8 x64 bottom

Would be default but for no password complexities To recreate UAC default GotoSecpol edit out Exit modify inf set export as Wins8x64inf and import using secedit cmd provided

echo off amp cls color 9F Title RUN AS Setlocal Verify local folder availability for script IF NOT EXIST CUtilities ( mkdir CUtilities amp GOTOGenBatch ) ELSE ( GotoGenBatch ) GenBatch c cd cd CUtilities IF NOT EXIST CUtilitiesBespokecmd ( GOTOCreateBatch ) ELSE ( GotoRunBatch )

CreateBatch Echo gtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo You have a royalty-free right to use modify reproduce and distribute

gtgtBespokecmd Echo the Sample Application Files (andor any modified version) in any way

gtgtBespokecmd Echo you find useful provided that you agree that the author provides

gtgtBespokecmd Echo has no warranty obligations or liability for any Sample Application

Files gtgtBespokecmd Echo ------------------------------------------------------------------------

gtgtBespokecmd Echo gtgtBespokecmd

Echo

gtgtBespokecmd Echo Sample batch script to demonstrate the usage of Bespokecmd

gtgtBespokecmd Echo gtgtBespokecmd Echo File Bespokecmd gtgtBespokecmd

Echo Date 10102013 gtgtBespokecmd Echo Version 101 gtgtBespokecmd

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 11: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Echo gtgtBespokecmd

Echo Main Function Allows for running of Bespoke batch with elevated rights and no future UAC pop-up gtgtBespokecmd

Echo gtgtBespokecmd Echo Usage Called and created by RunAscmd run from desired

location gtgtBespokecmd Echo Found in the CUtilities folder gtgtBespokecmd

Echo gtgtBespokecmd Echo Distributed under a GNU GPL type basis gtgtBespokecmd

Echo gtgtBespokecmd Echo Revisions gtgtBespokecmd

Echo 100 - 09102013 - Created gtgtBespokecmd Echo 101 - 10102013 - Modified added ability to temp disable UAC pop-up

warning gtgtBespokecmd Echo gtgtBespokecmd

Echo REFERENCES gtgtBespokecmd Echo gtgtBespokecmd Echo Exit code (ErrorLevel) 0 - No errors have occurred ie immediate

previous command ran successfully gtgtBespokecmd Echo Exit code (ErrorLevel) 1 - Errors occurred ie immediate previous

command ran Unsuccessfully gtgtBespokecmd Echo gtgtBespokecmd

Echo MS OS version check gtgtBespokecmd Echo httpmsdnmicrosoftcomen-

uslibrarywindowsdesktopms72483328v=vs8529aspx gtgtBespokecmd Echo gtgtBespokecmd

Echo Copying to certain folders and running certain apps require elevated perms gtgtBespokecmd

Echo Even with Run As perms UAC still pops up gtgtBespokecmd Echo gtgtBespokecmd

Echo To run a script or application in the Windows Shell gtgtBespokecmd Echo httpss64comvbshellexecutehtml gtgtBespokecmd

Echo gtgtBespokecmd Echo Machines joined to a corporate Domain should have the UAC feature set from and gtgtBespokecmd

Echo pushed out from a DC GPO policy gtgtBespokecmd Echo eg Computer Configuration - Policies - Windows Settings - Security

Settings - gtgtBespokecmd Echo Local PoliciesSecurity Options - User Account Control - gtgtBespokecmd

Echo Policy User Account Control Behavior of the elevation prompt for administrators gtgtBespokecmd

Echo in Admin Approval Mode Setting Elevate without prompting gtgtBespokecmd

Echo gtgtBespokecmd Echo

gtgtBespokecmd

EchogtgtBespokecmd Echo Echo off amp clsgtgtBespokecmd

Echo color 9FgtgtBespokecmd Echo Title RUN AS ADMINgtgtBespokecmd

Echo SetlocalgtgtBespokecmd EchogtgtBespokecmd Echo Set _OSVer=gtgtBespokecmd

Echo Set _OSVer=UACgtgtBespokecmd Echo VER | FINDSTR IL 5 gtNULgtgtBespokecmd

Echo IF ErrorLevel==0 SET _OSVer=PreUACgtgtBespokecmd Echo IF _OSVer==PreUAC GotoXPAdmingtgtBespokecmd

EchogtgtBespokecmd Echo Check if machine part of a Domain or within a Workgroup environment

gtgtBespokecmd Echo Set _DomainStat=gtgtBespokecmd

Echo Set _DomainStat=USERDOMAINgtgtBespokecmd Echo If i _DomainStat EQU computername (gtgtBespokecmd

Echo GotoWorkgroupMembergtgtBespokecmd Echo ) ELSE (gtgtBespokecmd

Echo Set _DomainStat=DomMember amp GotoDomainMembergtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo WorkgroupMembergtgtBespokecmd

Echo Verify status of Secpolmsc ConsentPromptBehaviorAdmin Reg key gtgtBespokecmd Echo reg query

HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin | Find i 0x0gtgtBespokecmd

EchogtgtBespokecmd Echo If ErrorLevel==0 (gtgtBespokecmd

Echo GotoBespokeBuildgtgtBespokecmd Echo ) Else (gtgtBespokecmd

Echo GotoDisUACgtgtBespokecmd Echo )gtgtBespokecmd

Echo DisUACgtgtBespokecmd Echo XPAdmingtgtBespokecmd

Echo DomainMembergtgtBespokecmd Echo Get ADMIN Privileges Start batch again modify UAC

ConsentPromptBehaviorAdmin reg if needed gtgtBespokecmd Echo gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe

SYSTEMROOTsystem32configsystemgtgtBespokecmd EchogtgtBespokecmd Echo IF Errorlevel NEQ 0 (gtgtBespokecmd

Echo echo Set objShell = CreateObject (ShellApplication ) gt tempgetadminvbsgtgtBespokecmd

Echo echo objShellShellExecute ~s0 runas 1 gtgt tempgetadminvbsgtgtBespokecmd

Echo tempgetadminvbsgtgtBespokecmd Echo del tempgetadminvbsgtgtBespokecmd

Echo exit BgtgtBespokecmd

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 12: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Echo ) else (gtgtBespokecmd

Echo pushd cdgtgtBespokecmd Echo cd d ~dp0gtgtBespokecmd

Echo echo offgtgtBespokecmd Echo )gtgtBespokecmd

EchogtgtBespokecmd Echo IF _OSVer==PreUAC GotoBespokeBuildgtgtBespokecmd

Echo IF _DomainStat==DomMember GotoBespokeBuildgtgtBespokecmd EchogtgtBespokecmd

Echo reg add HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v ConsentPromptBehaviorAdmin t REG_DWORD d 0 fgtgtBespokecmd

EchogtgtBespokecmd Echo BespokeBuildgtgtBespokecmd

Echo Add your script requiring elevated perm and no UAC below gtgtBespokecmd EchogtgtBespokecmd

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 PausegtgtBespokecmd

Echo GotoEOFgtgtBespokecmd

Echo EOFgtgtBespokecmd Echo ExitgtgtBespokecmd

Timeout T 1 NOBREAK gtNul RunBatch

call Bespokecmd Del F Q Bespokecmd

Secpol

Edit out the Exit (rem or ) to run amp 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 (

GotoWorkgroupPC ) ELSE (

Echo PC Member of a Domain Security Policy determined by GPO Pause

GotoEOF )

WorkgroupPC

reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo Machine already set for UAC Prompt

Pause GotoEOF

) else ( GotoEnableUAC

) EnableUAC

IF NOT EXIST CUtilitiesWins8x64Definf ( GOTOCreateInf ) ELSE (

GotoRunInf )

CreateInf This will create the default inf file and import it into the

local security policy for the Wins 8 machine Echo [Unicode]gtgtWins8x64Definf

Echo Unicode=yesgtgtWins8x64Definf Echo [System Access]gtgtWins8x64Definf

Echo MinimumPasswordAge = 0gtgtWins8x64Definf Echo MaximumPasswordAge = -1gtgtWins8x64Definf

Echo MinimumPasswordLength = 0gtgtWins8x64Definf Echo PasswordComplexity = 0gtgtWins8x64Definf

Echo PasswordHistorySize = 0gtgtWins8x64Definf Echo LockoutBadCount = 0gtgtWins8x64Definf

Echo RequireLogonToChangePassword = 0gtgtWins8x64Definf Echo ForceLogoffWhenHourExpire = 0gtgtWins8x64Definf

Echo NewAdministratorName = AdministratorgtgtWins8x64Definf Echo NewGuestName = GuestgtgtWins8x64Definf Echo ClearTextPassword = 0gtgtWins8x64Definf

Echo LSAAnonymousNameLookup = 0gtgtWins8x64Definf Echo EnableAdminAccount = 0gtgtWins8x64Definf

Echo EnableGuestAccount = 0gtgtWins8x64Definf Echo [Event Audit]gtgtWins8x64Definf

Echo AuditSystemEvents = 0gtgtWins8x64Definf Echo AuditLogonEvents = 0gtgtWins8x64Definf

Echo AuditObjectAccess = 0gtgtWins8x64Definf Echo AuditPrivilegeUse = 0gtgtWins8x64Definf

Echo AuditPolicyChange = 0gtgtWins8x64Definf Echo AuditAccountManage = 0gtgtWins8x64Definf

Echo AuditProcessTracking = 0gtgtWins8x64Definf Echo AuditDSAccess = 0gtgtWins8x64Definf

Echo AuditAccountLogon = 0gtgtWins8x64Definf

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 13: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Echo [Registry Values]gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindows NTCurrentVersionSetupRecoveryConsoleSecurityLevel=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionSetupRecoveryConsoleSetCommand=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonCachedLogonsCount=110gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonForceUnlockLogon=40gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonPasswordExpiryWarning=45gtgtWins8x64Definf Echo MACHINESoftwareMicrosoftWindows

NTCurrentVersionWinlogonScRemoveOption=10gtgtWins8x64Definf Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorAdmin=45gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemConsentPromptBehaviorUser=43gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableCAD=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDontDisplayLastUserName=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableInstallerDetection=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableLUA=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableSecureUIAPaths=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableUIADesktopToggle=40gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemEnableVirtualization=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemFilterAdministratorToken=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemPromptOnSecureDesktop=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemScForceOption=40gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemShutdownWithoutLogon=41gtgtWins8x64Definf

Echo

MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemUndockWithoutLogon=41gtgtWins8x64Definf

Echo MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemValidateAdminCodeSignatures=40gtgtWins8x64Definf

Echo

MACHINESoftwarePoliciesMicrosoftWindowsSaferCodeIdentifiersAuthenticodeEnabled=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaAuditBaseObjects=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaCrashOnAuditFail=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaDisableDomainCreds=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaEveryoneIncludesAnonymous=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaFIPSAlgorithmPolicyEnabled=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaForceGuest=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaFullPrivilegeAuditing=30gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaLimitBlankPasswordUse=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinClientSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaMSV1_0NTLMMinServerSec=4536870912gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlLsaNoLMHash=41gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymous=40gtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 14: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

MACHINESystemCurrentControlSetControlLsaRestrictAnonymousSAM=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlPrintProvidersLanMan Print ServicesServersAddPrinterDrivers=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedExactPathsMachine=7SystemCurrentControlSetControlProductOptionsSystemCurrentControlSetControlServer

ApplicationsSoftwareMicrosoftWindows NTCurrentVersiongtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetControlSecurePipeServersWinregAllowedPathsMachine=7SystemCurrentControlSetControlPrintPrintersSystemCurrentControlSetServicesEventlogSoftwareMicrosoftOLAP ServerSoftwareMicrosoftWindows NTCurrentVersionPrintSoftwareMicrosoftWindows

NTCurrentVersionWindowsSystemCurrentControlSetControlContentIndexSystemCurrentControlSetControlTerminal ServerSystemCurrentControlSetControlTerminal

ServerUserConfigSystemCurrentControlSetControlTerminal ServerDefaultUserConfigurationSoftwareMicrosoftWindows NTCurrentVersionPerflibSystemCurrentControlSetServicesSysmonLoggtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetControlSession

ManagerKernelObCaseInsensitive=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession ManagerMemory

ManagementClearPageFileAtShutdown=40gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerProtectionMode=41gtgtWins8x64Definf Echo MACHINESystemCurrentControlSetControlSession

ManagerSubSystemsoptional=7PosixgtgtWins8x64Definf Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersAutoDisconnect=415gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersEnableForcedLogOff=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersEnableSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersNullSessionPipes=7gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanManServerParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanManServerParametersRestrictNullSessAccess=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnablePlainTextPassword=40gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersEnableSecuritySignature=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLanmanWorkstationParametersRequireSecuritySignature=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesLDAPLDAPClientIntegrity=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersDisablePasswordChange=40gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersMaximumPasswordAge=430gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersRequireSignOrSeal=41gtgtWins8x64Definf

Echo MACHINESystemCurrentControlSetServicesNetlogonParametersRequireStrongKey=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSealSecureChannel=41gtgtWins8x64Definf

Echo

MACHINESystemCurrentControlSetServicesNetlogonParametersSignSecureChannel=41gtgtWins8x64Definf

Echo [Privilege Rights]gtgtWins8x64Definf Echo SeNetworkLogonRight = S-1-1-0S-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeBackupPrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeChangeNotifyPrivilege = S-1-1-0S-1-5-19S-1-5-20S-1-5-32-544S-1-5-32-545S-1-5-32-551S-1-5-90-0gtgtWins8x64Definf

Echo SeSystemtimePrivilege = S-1-5-19S-1-5-32-544gtgtWins8x64Definf Echo SeCreatePagefilePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeDebugPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeRemoteShutdownPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeAuditPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeIncreaseQuotaPrivilege = S-1-5-19S-1-5-20S-1-5-32-

544gtgtWins8x64Definf Echo SeIncreaseBasePriorityPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeLoadDriverPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeBatchLogonRight = S-1-5-32-544S-1-5-32-551S-1-5-32-559gtgtWins8x64Definf

Echo SeServiceLogonRight = S-1-5-80-0S-1-5-83-0gtgtWins8x64Definf Echo SeInteractiveLogonRight = GuestS-1-5-32-544S-1-5-32-545S-1-5-32-

551gtgtWins8x64Definf Echo SeSecurityPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemEnvironmentPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeProfileSingleProcessPrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeSystemProfilePrivilege = S-1-5-32-544S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420gtgtWins8x64Definf

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 15: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

Echo SeAssignPrimaryTokenPrivilege = S-1-5-19S-1-5-20gtgtWins8x64Definf Echo SeRestorePrivilege = S-1-5-32-544S-1-5-32-551gtgtWins8x64Definf

Echo SeShutdownPrivilege = S-1-5-32-544S-1-5-32-545S-1-5-32-551gtgtWins8x64Definf

Echo SeTakeOwnershipPrivilege = S-1-5-32-544gtgtWins8x64Definf Echo SeDenyNetworkLogonRight = GuestgtgtWins8x64Definf

Echo SeDenyInteractiveLogonRight = GuestgtgtWins8x64Definf Echo SeUndockPrivilege = S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeManageVolumePrivilege = S-1-5-32-544gtgtWins8x64Definf

Echo SeRemoteInteractiveLogonRight = S-1-5-32-544S-1-5-32-555gtgtWins8x64Definf Echo SeImpersonatePrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeCreateGlobalPrivilege = S-1-5-19S-1-5-20S-1-5-32-544S-1-5-

6gtgtWins8x64Definf Echo SeIncreaseWorkingSetPrivilege = S-1-5-32-545S-1-5-90-0gtgtWins8x64Definf

Echo SeTimeZonePrivilege = S-1-5-19S-1-5-32-544S-1-5-32-545gtgtWins8x64Definf Echo SeCreateSymbolicLinkPrivilege = S-1-5-32-544S-1-5-83-0gtgtWins8x64Definf

Echo [Version]gtgtWins8x64Definf Echo signature=$CHICAGO$gtgtWins8x64Definf

Echo Revision=1gtgtWins8x64Definf

RunInf Import Wins8x64Definf with ADMIN Privileges to modify UAC

ConsentPromptBehaviorAdmin reg gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

IF Errorlevel NEQ 0 ( echo Set objShell = CreateObject(ShellApplication) gt

tempgetadminvbs echo objShellShellExecute ~s0 runas 1 gtgt

tempgetadminvbs tempgetadminvbs

del tempgetadminvbs exit B

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

GotoCheckUAC ) else (

Secedit configure db seceditsdb cfg CUtilitiesWins8x64Definf overwrite

echo off )

CheckUAC reg query HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem v

ConsentPromptBehaviorAdmin | Find i 0x5 Echo

If ErrorLevel==0 ( Echo ConsentPromptBehaviorAdmin set to Prompt

Pause Del Q CUtilitiesWins8x64Definf

GotoEOF ) else (

Echo ConsentPromptBehaviorAdmin NOT set to default Pause

) ENDLOCAL

EOF Exit

Domain PCs should be governed as much as possible by GPO sets WorkgroupStandalone

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 seceditexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTsystem32configsystem

By running only SYSTEMROOTsystem32caclsexe or

SYSTEMROOTsystem32configsystem or both from the command prompt - elevated or

not check the result across the board

answered Oct 13 13 at 1727

Ian Stockdale

1

Note Checking with cacls for system32configsystem will ALWAYS fail in WOW64 (for

example from systemrootsyswow64cmdexe 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

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 16: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

in 32bit shell in 64bit system will loop forever Better would be checking for rights on Prefetch

directory

gtnul 2gtamp1 SYSTEMROOTsystem32caclsexe SYSTEMROOTPrefetch

Win XP to 7 tested however it fails in WinPE as in windows 7 installwim there is no such dir nor

caclsexe

Also in winPE AND wow64 fails check with openfilesexe

OPENFILES gt 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

in Windows XP - 8 3264 bit in WOW64 and in WinPE are dir creation tests (IF

admin didnt carpet bombed Windows directory with permissions for everyone) and

What works

net session

and

reg add HKLM F

checks

Also one more note in some windows XP (and other versions probably too depending on admins

tinkering) depending on registry entries directly calling batcmd from vbs script will fail with info

that batcmd files are not associated with anything

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

Calling cmdexe with parameter of batcmd file on the other hand works OK

echo Set UAC = CreateObject(ShellApplication) gt tempgetadminvbs

echo UACShellExecute cmdexe C ~s0 runas 1 gtgt tempgetadminvbscscript tempgetadminvbs nologo

edited Dec 2 13 at 1617 answered Oct 21 13 at 1100

user2902818

1 1

Alternative Use an external utility that is designed for this purpose eg (unrestricted

freeware)

IsAdminexe

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 1831

Bill_Stewart

3460 9 15

echo off

verset ADMDIR=CUsersAdministrator

dir ADMDIR 1gtnul 2gtamp1echo [errorlevel] ADMDIR

if errorlevel==0 goto main further checks eg try to list the contents of admin folders

wherever they are stored on older versions of Windowsecho You need administrator privileges to run this script 0

echo Exitingexit b

mainecho Executing with Administrator privileges

answered Nov 29 14 at 2211

cmd

1

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 17: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

echo off

startset randname=randomrandomrandomrandomrandom

md windowsrandname 2gtnulif errorlevel==0 (echo Youre elevated

goto end)if errorlevel==1 (echo Youre not elevated ((goto end)

goto startend

rd windowsrandname 2gtnulpause gtnul

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=randomrandomrandomrandomrandom

Set the filename of the directory to be created

md windowsrandname 2gtnul

Creates the directory on (replace ltDLgt with drive letter)ltDLgtWindows

if errorlevel==0 (echo Youre elevatedgoto end)

If the ERRORLEVEL environment variable is zero then echo success message

Go to the end (dont proceed any further)

if errorlevel==1 (echo Youre 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 command will

not let this run)

goto end

end

Specify the ending point

rd windowsrandname 2gtnul

Remove the created directory

pause gtnul

Pause so the user can see the message

The and are filtering the output of these commandsNote gtnul 2gtnul

answered Apr 22 at 1450

erikkonstas

25 5

ndash

Yes I know that when you are logged in as the Administrator user (not a user with admin account type) youwill be always elevated but thats not a bug erikkonstas Apr 22 at 1455

The whoami groups doesnt work in one case If you have UAC totally turned off (not just

notification turned off) you started from an Administrator prompt then issuedand

runas trustlevel0x20000 cmd

you will be running non-elevated but issuing

whoami groups

will say youre elevated Its wrong Heres why its wrong

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257

Page 18: Windows - Batch Script_ How to Check for Admin Rights - Stack Overflow

When running in this state if IsUserAdmin (

) returns FALSE and UAC is fully disabled

and GetTokenInformation returns TokenElevationTypeDefault

(

) then the process is running elevated but

claims it is

httpsmsdnmicrosoftcomen-

uslibrarywindowsdesktopaa376389(v=vs85)aspx

httpblogsmsdncombcjacksarchive20061024modifying-the-mandatory-integrity-level-for-a-

securable-object-in-windows-vistaaspx not whoami

groups

really the best way to do this from a batch file is

net session gtnul 2gtnulnet session gtnul 2gtnul

echo errorlevel

You should do twice because if someone did an before hand youll get the

wrong information

net session at

answered Jun 18 at 1724

zumalifeguard

3822 2 12 25

ndash

is not providing the wrong information Its just that puts you in an

unexpected place running without administrator privileges but with high integrity level You can confirm thiswith Process Explorer (This may be a bug in but is not a bug in )

whoami groups runas trustlevel

runas whoami Harry Johnston Jun

18 at 2210

ndash

Harry I hear what youre saying but can you elaborate on this I dont understand the comment with regardto When youre 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 cannotperform admin operations Try net session or fsutil or any other utility that requires administrator accessHowever whoami groups tells you youre elevated When youre not The fact that callingGetTokenInformation returns TokenElevationTypeDefault indicates that

runas trustlevel

zumalifeguard Jun 19 at 142

ndash

Im not sure that I understand what you mean by whoami groups tells you youre elevated it doesntliterally output the string youre elevated does it What part of the output of whoami groups are youlooking at Harry Johnston Jun 19 at 207

ndash

Harry I see I wasnt clear First background so you and I are on the same page there a handful of trickspeople use in determining whether a command prompt is currently running in a state that has administratoraccess Common techniques are to use the built command such as fsutil at whoami and net sessionUsing at is deprecated If you search this page you will see examples using fsutil whoami and netsession See here for more examples of whoami stackoverflowcomquestions7985755hellip zumalifeguardJun 19 at 1543

ndash

Also using the phrase running elevated is not exactly correct What I (and others) should say runningwith administrator privilege If UAC is turned off thats simply running while logged on as local admin but notexplicitly lowered trust-level such as with runas When UAC is enabled this means the user is running in anelevated prompt zumalifeguard Jun 19 at 1545

Another way to do this

REM CHECKING OR IS STARTED AS ADMINISTRATOR

FSUTIL | findstr I volume gt nulampif not errorlevel 1 goto Administrator_OK

clsecho

echo R U N A S A D M I N I S T R A T O R echo

echoecho

echo Call up just as the Administrator Abbreviation can be done to the script and set

echoecho Shortcut gt Advanced gt Run as Administratorecho

echoecho Alternatively a single run Run as Administrator

echo or in the Schedule tasks with highest privilegespause gt nul

gotoeofAdministrator_OK

REM Some next lines code

edited Apr 7 at 2310

Michael Myers diams992k 26 211 250

answered Apr 7 at 2252

Artur Zgadzaj

1 2

ndash What is that link supposed to be Flagged as spam because of the link mmgross Apr 7 at 2257