Anyone know anything about batch files and uac elevation?

i tried posting a question on stackoverflow here, but all i got was four different “solutions” that informed me about things that were of no bearing to the issue and a couple of questions about what i was going to use it for. working as expected, and when the wife said those folks were rude and not me, i told her if i had posted it here i’d have three answers by now. then it clicked, so here we are.

basically, i am making a menu driven batch file that does some things that require elevation to admin rights and is supposed to popup the box asking for the password and then elevate the command prompt. i got some code from one site that worked, then i left it alone for six months and came back to it and it doesn’t work now. so i got some other code that did the same thing that was a bit longer and it doesn’t even pop up the uac box.

this is the batch file:
:nauseated_face:
echo off
cls
:: check if we are admin
:-------------------------------------
REM → Check for permissions

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

REM → If error flag set, we do not have admin.
if ‘%errorlevel%’ NEQ ‘0’ (
echo Requesting administrative privileges…
goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
echo Set UAC = CreateObject^(“Shell.Application”^) > “%temp%\getadmin.vbs”
echo UAC.ShellExecute “%~s0”, “”, “”, “runas”, 1 >> “%temp%\getadmin.vbs”

"%temp%\getadmin.vbs"
exit /B

:gotAdmin
if exist “%temp%\getadmin.vbs” ( del “%temp%\getadmin.vbs” )
pushd “%CD%”
:--------------------------------------
:menu
cls
ECHO.
ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ECHO What would you like to do? Type 4 to exit.
ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ECHO.
ECHO 1 - Clear the print spooler
ECHO 2 - Restore network connectivity
ECHO 3 - Get computer information
ECHO 4 - Exit
ECHO.

SET /P M=Type 1, 2, 3, or 4 then press ENTER:
IF %M%==1 GOTO print
IF %M%==2 GOTO network
IF %M%==3 GOTO compinfo
IF %M%==4 GOTO EOF

:print
@echo off
net stop spooler
pause
cd c:\windows\system32\spool\printers
pause
whoami
pause
::del /Q .
pause
net start spooler
goto menu

:network
@echo off
ipconfig /release
ipconfig /renew
ipconfig /flushdns
ipconfig /registerdns
netsh dump
nbtstat -R
netsh int ip reset reset.log
netsh winsock reset
echo You need to restart now to finish configuration changes…
::set /p answer=Restart now?
::if %answer%=“y” shutdown /r /t 0 else
::if %answer%=“yes” shutdown /r /t 0 else
pause
goto menu

:compinfo
@echo off
REM set variables
set computer=
set system=
set manufacturer=
set model=
set serialnumber=
set osname=
set sp=
set cstring=
set ustring=
set pstring=

FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% OS Get csname /value’) do SET computer=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% OS Get csname /value’) do SET system=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% ComputerSystem Get Manufacturer /value’) do SET manufacturer=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% ComputerSystem Get Model /value’) do SET model=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% Bios Get SerialNumber /value’) do SET serialnumber=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% os get Name /value’) do SET osname=%%A
FOR /F “tokens=1 delims=‘|’” %%A in (“%osname%”) do SET osname=%%A
FOR /F “tokens=2 delims=‘=’” %%A in (‘wmic %cstring% %ustring% %pstring% os get ServicePackMajorVersion /value’) do SET sp=%%A

echo done!

echo ----------------
echo System Name: %system%
echo Manufacturer: %manufacturer%
echo Model: %model%
echo Serial Number: %serialnumber%
echo Operating System: %osname%
echo Service Pack: %sp%
echo ----------------

REM Generate file
SET file=“%~dp0%computer%.txt”
echo ---------------- > %file%
echo Details For %computer%: >> %file%
echo System Name: %system% >> %file%
echo Manufacturer: %manufacturer% >> %file%
echo Model: %model% >> %file%
echo Serial Number: %serialnumber% >> %file%
echo Operating System: %osname% >> %file%
echo Service Pack: %sp% >> %file%
echo ---------------- >> %file%

echo File created at %file%

REM request user to push any key to continue
pause
goto menu

and this is the uac code i used after that didn’t work:
:face_vomiting:
:: check if we are admin
:-------------------------------------
::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see “windows - How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required? - Stack Overflow” for description
::::::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================

:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set “batchPath=%~dpnx0”
rem this works also from cmd shell, other than %~0
for %%k in (%0) do set batchName=%%~nk
set “vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs”
setlocal EnableDelayedExpansion

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

:getPrivileges
if ‘%1’==‘ELEV’ (echo ELEV & shift /1 & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************

ECHO Set UAC = CreateObject^(“Shell.Application”^) > “%vbsGetPrivileges%”
ECHO args = "ELEV " >> “%vbsGetPrivileges%”
ECHO For Each strArg in WScript.Arguments >> “%vbsGetPrivileges%”
ECHO args = args ^& strArg ^& " " >> “%vbsGetPrivileges%”
ECHO Next >> “%vbsGetPrivileges%”

if ‘%cmdInvoke%’==‘1’ goto InvokeCmd

ECHO UAC.ShellExecute “!batchPath!”, args, “”, “runas”, 1 >> “%vbsGetPrivileges%”
goto ExecElevation

:InvokeCmd
ECHO args = “/c “”” + “!batchPath!” + “”" " + args >> “%vbsGetPrivileges%”
ECHO UAC.ShellExecute “%SystemRoot%%winSysFolder%\cmd.exe”, args, “”, “runas”, 1 >> “%vbsGetPrivileges%”

:ExecElevation
“%SystemRoot%%winSysFolder%\WScript.exe” “%vbsGetPrivileges%” %*
exit /B

:gotPrivileges
setlocal %~dp0
if ‘%1’==‘ELEV’ (del “%vbsGetPrivileges%” 1>nul 2>nul & shift /1)

::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
REM Run shell as admin (example) - put here code as you like

:grimacing:
sorry about the huge post but we don’t have code formatting here like they do at stackoverflow, go figure. this is the error message i get from the first menu:


this is from the second uac elevation code:
batch-error-uac
this error comes at the end of the script and the uac box never pops up. it seems like there is something wrong with the script but i can’t find it to check. it has to be talking about the vb script it’s calling because this batch file doesn’t have that many characters in line 1. any help is appreciated. maybe @FieldEffect or @Nitt?

so i fed your post here into chatgpt(chat.openai.com) and it came up with a few things.
Oh, and you can use [ code ] [ /code ] to put things into a code format on here. no spaces tho.

So for the first part, instead of using vbscript, it suggested changing it to powershell

@echo off
cls

:: Check if we are admin
net session >nul 2>&1
if %errorlevel% == 0 (
    goto admin
) else (
    echo Requesting administrative privileges...
    powershell -command "Start-Process cmd -ArgumentList '/c %~0' -Verb RunAs"
    exit
)

:admin
echo Running with admin privileges.
pause

:--------------------------------------
:menu

And the last half, it complained about extra quotations and whatnot, gave me this

@echo off
CLS

:init
setlocal DisableDelayedExpansion
set cmdInvoke=1
set winSysFolder=System32
set "batchPath=%~dpnx0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion

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

:getPrivileges
if "%1"=="ELEV" (shift /1 & goto gotPrivileges)
set args=%*
set args=%args:"=""%
set cmd=%SystemRoot%\system32\cmd.exe
if "%cmdInvoke%"=="1" goto InvokeCmd
set cmdInvoke=1
powershell -command "Start-Process -FilePath '%cmd%' -ArgumentList '/c %~0 %args:'='% /k' -Verb RunAs" && exit

:InvokeCmd
set args=%args:/c "="%
set cmd="%SystemRoot%%winSysFolder%\cmd.exe"
goto ExecElevation

:ExecElevation
"%SystemRoot%%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %cmd% %args%
exit /B

:gotPrivileges
setlocal %~dp0
if "%1"=="ELEV" (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)

::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
REM Run shell as admin (example) - put here code as you like

with these changes, the script functions, maybe it’s what you want?

3 Likes

Much cleaner… looks good.

Not going to deep dive but you are calling setlocal with an incorrect parameter “%~dp0” which is the currently running env path without quotes…the %~dp0 is more likely meant to come after a “cd” command.so it changes you to the correct directory… which I am reading is an issue you have incurred

…and this site does support markdown…code is best viewed in a code block or a block quote:

this is a code block

This relevant link regarding the correct values that setlocal can be sent is in a block quote
Setlocal - Local variables - Windows CMD - SS64.com

2 Likes

This is complete jibberish to me, I don’t know how u guys do it :man_facepalming:t2:

4 Likes

Some are Pro’s others like me self read a lot, here is a great start on learning for free. https://www.pdfdrive.com/

3 Likes

Gracias @avr1

1 Like

i tried it and it almost works, it shows the cmd window, then says requesting admin privileges, then the header changes to the system32 folder on the cmd window and then it goes away.

that came with the code snippet i got and i had to comment it out for it to halfway work. it made the batch file delete the files in the folder it started in including itself.

the lesson i am trying to get across is how to do this. it was for entry level techs and was about automating things with batch scripts and powershell scripts. i had it done about six months ago with the top code block then something changed somewhere and it doesn’t work now. i had a good idea of what was going on until the extra powershell crap got added in and now it has me scratching my head a tad.

i had a handle on it until it started getting complicated. now i’m getting confused a little since i’m mixing powershell with a batch file. throw a little python and rust in there and my head may explode. i just need to sit down and get real high and tear it apart line by line for a few hours and see what is going on.

now that i know how to make a code block and after i realized that i don’t need the whole thing to just run option 1 and test it, if anyone wants to run the following code and see if that will work, all it does is attempt to clear the print spool after getting admin rights. i commented out the delete part in case the admin rights go and it stays in the system32 folder.

:: check if we are admin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
:--------------------------------------
:menu
cls
ECHO.
ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ECHO What would you like to do? Type 4 to exit.
ECHO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ECHO.
ECHO 1 - Clear the print spooler
ECHO 2 - Restore network connectivity
ECHO 3 - Get computer information
ECHO 4 - Exit
ECHO.

SET /P M=Type 1, 2, 3, or 4 then press ENTER:
IF %M%==1 GOTO print
IF %M%==2 GOTO network
IF %M%==3 GOTO compinfo
IF %M%==4 GOTO EOF

:print
@echo off
net stop spooler 
pause
cd c:\windows\system32\spool\printers 
pause
whoami
echo %cd%
pause
::del /Q *.* 
pause
net start spooler
goto menu```

Delete.exe!

1 Like

that means it’s my computer than. i wonder what the hell is wrong with it? i even tried a new profile and another windows 10 computer. this is what i get now, weird as hell like it’s possessed and getting worse.
wtf

Did you right click the cmd icon in the Taskbar and “Run as administrator”?
You may be in the local admin user account but all command terminals start with non-administrative access and dont have the permissions necessary to affect system changes.

of course not, that kind of takes away the function of having the uac box pop up and ask for the admin password. that’s the whole point it.

Cool. Try it, look at the error message, and change the relevant permissions.

man, it’s getting weird as hell around here now. i was screwing around with this 2 hrs ago getting whacked out results. now, after hitting a bong a few times and closing everything down and getting ready to shut down i noticed the batch file still running. i hit enter and it cleared up. when i hit enter again it ran, didn’t work elevated yet, but not showing the same screwy results i took screencaps of 2 hrs ago. look:


there are no relevant permissions, it is running from system32, says it is admin user when i run whoami, but has access denied to change directory to print spool. it should have access as i can do it through the gui and windows explorer. the first access denied is changing to spool, the next command is whoami, the next is echo %cd%.

Understood. Now open an administrative terminal window and cd spool\printers…you will already be in system32 folder.
The permission denied shows the need for further modification of your PRINTERS folder permissions.

1 Like

yes, and the code snip at the top of my batch file asks for, and receives, the admin password at the uac prompt when the box pops up. when the batch file starts, it is ran from the regular folder it started in, then the uac prompt changes it to the system32 folder when it receives admin rights. the admin rights do not work any longer as it no longer has admin permission to change directory to the spool. that is the whole point of the batch file, for someone who is a standard user to click on, put in the admin password, then clear their own print spool without the help of myself. i’ve done it before, and this one worked six months ago, in december when i wrote it for the other section of the book i am writing. now it no longer works on my computer. did it work on yours without running as admin and do you you know how i can fix it? with the addition of this powersehll crap to my batch file i no longer know exactly what i am doing.

the second part of the code i posted in the original comment had another snip of code that was supposed to do the same thing but never did pop up the uac box. i am assuming from the output of the one error that there is something corrupted in the powershell script at line 1, position 11, that is preventing it from executing, but cannot seem to find where powershell keeps the scripts. that is my next search, but i figured that someone here may know about it to help out. i already received much more help here than at stackoverflow and it was all a much nicer tone as well.

ok, now it doesn’t work if i right click and say run as admin. so i am completely stumped. i then navigated to the print spool and opened a powershell window there with no uac prompt and it allowed me to delete the file. it also didn’t ask me for the password when i created the file. yet i get access denied when running an admin terminal. all on a standard user. if it weren’t for steam i’d give up windows completely. any ideas anyone?

upon further troubleshooting, it appears to be a system issue, not with the code. i cannot run the menu by runas admin, nor can i change directories with cmd terminal. powershell will open an admin shell in the print spool and delete files without uac prompt. i can create and delete files there without uac prompt in the gui, whereas yesterday it required a password. the cmd terminal is still restricted from it even though everything else allows it. if anyone else has any other ideas or things to try i will try them. otherwise it will be a reinstall of the os. first on the laptop just in case. i hate reinstalling the gaming system. thanx for the help and ideas.

1 Like

any spaces in the paths?

nope. cd c:\windows\system32\spool\printers. it works with powershell, and it shouldn’t without asking for elevation. that is the truly weird part now, it seems the whole uac part of the system is hosed.

at least before i could also run it as admin and it worked, but now that doesn’t work either. i have a few months to figure it out but i do need to learn how to fix it.