Solved Batch File on USB fails when Ran As Administrator

JaoJack

New member
Local time
12:54 AM
Messages
3
I am new to this site so please excuse any lack of etiquette I may show. I have recently built a .bat files to perform a large number of configuration changes needed for a Win7 or Win8 workstation to function properly on my network.


The .bat file obviously needs to be ran with elevated privileges due to the changing security options it performs. The .bat file runs perfectly for me from the local HDD but as soon as I copy it to a USB it fails to launch when ran as administrator.


With that said, I can execute the .bat with standard rights and it will launch as expected, but trying as administrator simply flashes a quick cmd box and then closes.


I have taken this down to the most basic of batch files and it seems no .bat will run as administrator from a USB for me on either Win7 or Win8 which leads me to believe this is not an issue with my actual .bat file.


Has anyone else experienced this? is the only way to execute going to be to copy the file to the local HDD before running it? If so, can it be made to delete itself once it completes?


Ideally, if it can be made to copy to the HDD, run as administrator, and then delete itself when it was done it would almost be fool proof.


Thank you in advance.
 

My Computer My Computer

Computer type
PC/Desktop
OS
Windows 7 Pro x64 / Windows 8.1 Pro x64
The problem was with the directory name on the USB. It contained an "&" symbol. discovered by using %~f0 and %~dp0
 

My Computer My Computer

Computer type
PC/Desktop
OS
Windows 7 Pro x64 / Windows 8.1 Pro x64
The problem was with the directory name on the USB. It contained an "&" symbol. discovered by using %~f0 and %~dp0

I recently came across the same issue and was going to tell you this, until I saw your second post :)


You might also find this coding interesting so you do not need to remember to right click and run as admin. It will auto prompt for uac elevation and away you go!

Code:
:: BatchGotAdmin
:-------------------------------------
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%"


    CD /D "%~dp0"

:--------------------------------------
 

My Computer My Computer

Computer type
PC/Desktop
Computer Manufacturer/Model Number
Custom Built
OS
Windows 10 Pro
CPU
AMD Ryzen 5 2400G Processor with Radeon RX Vega 11 Graphics
Motherboard
ASRock X470 Master SLI/AC AM4 AMD Promontory X470 SATA 6Gb/s
Memory
G.SKILL Ripjaws V Series 16GB (2 x 8GB) 288-Pin DDR4 SDRAM D
Graphics Card(s)
2047MB NVIDIA GeForce GTX 1060 6GB (EVGA)
Sound Card
Motherboard Built in
Monitor(s) Displays
Acer R240HY bidx 23.8-Inch IPS HDMI DVI VGA (1920 x 1080) Wi
Screen Resolution
1920 x 1080
Hard Drives
1TB Sandisk SSD PLUS (Main drive)
500 GB Seagate 7200 RPM (Games)
500 GB Western Digital 7200 RPM (Virtual Machines)
PSU
CORSAIR TX Series TX650M 650W 80+ Gold Modular Power Supply
Case
CORSAIR CARBIDE SPEC-02 Mid-Tower Gaming Case, Red LED Fan
Cooling
220mm, two 120mm, and four 60mm fans
Keyboard
Wired Dell keyboard
Mouse
Wireless Logitech mouse
Internet Speed
250mb down, 30mb up
Antivirus
Panda Cloud Antivirus
Browser
Chrome-ish x64
Other Info
Your awesome for reading this.
Andrew,


Thank you for taking the time to send my your tip. I am actually using a variation of the same code. I use "fsutil dirty" to determine the rights instead of "cacls".


With some slight rework and research, I was finally able to complete my script to do almost everything I wanted it to. It opens and runs as admin, prompts with a "Yes / No" message box for each step for confirmation, logs its progress, copies itself to the startup folder, reboots the system, re-runs itself to pick up where it left off, and then deletes itself when it finishes.


Below is a very condensed version (actual version performs a crap-ton of steps). Anyhow, posted here in case anyone else can use it.

Code:
@echo off 
cls
color f0

call :progress 0



REM ---------------------------------------------------------------------------------------------------------------------------------



:CHECKINGRIGHTS

call :isAdmin

if %errorlevel% == 0 (

   goto :gotAdmin

   ) else (

   echo.
   echo.
   echo Requesting Elevated Privilages... 
   echo.
   echo.
   echo 	ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
   echo 	º                                                              º
   echo 	º  You must click "Yes" on the "User Account Control" pop-up.  º
   echo 	º                                                              º
   echo 	ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ

   goto :UACPrompt

)



: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%"
    CD /D "%~dp0"
    goto :START



:isAdmin

fsutil dirty query %systemdrive% >nul

exit /b



REM ---------------------------------------------------------------------------------------------------------------------------------



:START

Echo.
Echo.
Echo 	ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
Echo 	º                                                              º
Echo 	º    Welcome to the Configurations and Settings Application!   º
Echo 	º                                                              º
Echo 	ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
Echo.
Echo.



REM ---------------------------------------------------------------------------------------------------------------------------------



:SETUPLOGS

   if exist "c:\Install Logs" goto :STEP1

   md "c:\Install Logs"



REM ---------------------------------------------------------------------------------------------------------------------------------



:STEP1

if exist "C:\Install Logs\1.log" goto :DONE1

echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp1.vbs
echo WScript.Quit (WshShell.Popup( "Step 1" + CHR(13) + CHR(13) + "Would you like to do your task?" + CHR(13), , "Step 1 - Your Task", 4 + 32)) >> %tmp%\tmp1.vbs
cscript /nologo %tmp%\tmp1.vbs

if %errorlevel%==6 (

   REM ***ENTER YOUR COMMAND FOR STEP 1 HERE***

   cls

   for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
   set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
   echo Local Administrator Set Active [%ldt%] >> "C:\Install Logs\1.log"

   for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
   set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
   echo Local Administrator Set Active [%ldt%] >> "C:\Install Logs\ReBoot.Needed.log"
  
  ) else (

    if %errorlevel%==7 (

    goto :DONE1
 
    ) else (

    goto :ERROR

  )

)


   del %tmp%\tmp1.vbs

   echo.
   echo Step 1 - Complete
   msg %username% /w Your Task was completed.
 


:DONE1

call :progress 33



REM ---------------------------------------------------------------------------------------------------------------------------------



:STEP2

if exist "C:\Install Logs\2.log" goto :DONE2

echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp2.vbs
echo WScript.Quit (WshShell.Popup( "Step 2" + CHR(13) + CHR(13) + "Would you like to do your task?" + CHR(13), , "Step 2 - Your Task", 4 + 32)) >> %tmp%\tmp2.vbs
cscript /nologo %tmp%\tmp2.vbs

if %errorlevel%==6 (

   REM ***ENTER YOUR COMMAND FOR STEP 2 HERE***

   cls

   for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
   set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
   echo Remote Desktop Access Enabled [%ldt%] >> "C:\Install Logs\2.log"

  ) else (

    if %errorlevel%==7 (

    goto :DONE2
 
    ) else (

    goto :ERROR

  )

)


   del %tmp%\tmp2.vbs

   echo.
   echo Step 1 - Complete
   echo Step 2 - Complete
   msg %username% /w Your Task was completed.
 


:DONE2

call :progress 66



REM ---------------------------------------------------------------------------------------------------------------------------------




:TEMPMAPDRIVE

   if exist "C:\Install Logs\ReBoot.Needed.log" goto :REBOOTNEEDED

	echo.
	echo.

	rem net use x: /delete /yes
	net use x: \\SERVERNAME\FOLDERNAME /user:DOMAIN\Administrator

	cls
	echo.
        echo Step 1 - Complete
        echo Step 2 - Complete




REM ---------------------------------------------------------------------------------------------------------------------------------



:STEP3

   if exist "C:\Install Logs\3.log" goto :DONE3

echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp3.vbs
echo WScript.Quit (WshShell.Popup( "Step 3" + CHR(13) + CHR(13) + "Would you like to install your app?" + CHR(13), , "Step 3 - Install Your Application", 4 + 32)) >> %tmp%\tmp3.vbs
cscript /nologo %tmp%\tmp3.vbs

if %errorlevel%==6 (

   if exist "C:\Program Files (x86)\APPLICATION" goto :LOG3

   "x:\APPLICATION\Setup.exe"
     
  ) else (

    if %errorlevel%==7 (

    goto :DONE3
 
    ) else (

    goto :ERROR

  )

)



:LOG3

   del %tmp%\tmp3.vbs

   if not exist "C:\Program Files (x86)\McAfee" goto :DONE3

   for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
   set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
   echo McAfee installation verified [%ldt%] >> "C:\Install Logs\3.log"

    

:DONE3

call :progress 99
echo Step 3 - Complete



REM ---------------------------------------------------------------------------------------------------------------------------------



:REMOVETEMPDRIVE

   net use x: /delete /yes

   cls
   echo.
   echo Step 1 - Complete
   echo Step 2 - Complete
   echo Step 3 - Complete



REM ---------------------------------------------------------------------------------------------------------------------------------



:END

call :progress 100

if "%~f0" == "%userprofile%\AppData\Roaming\MICROS~1\Windows\STARTM~1\Programs\Startup\%~nx0" ( goto :CLEANUP )

msg %username% /w All steps have completed.

Exit



:CLEANUP

msg %username% /w All steps have completed.

call :deleteSelf&exit /b



:deleteSelf

start /b "" cmd /c del "%~f0"&exit /b

Exit



REM ---------------------------------------------------------------------------------------------------------------------------------



:REBOOTNEEDED

   if exist "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\%~nx0" goto :COPYDONE
   copy "%~f0" "%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\%~nx0"
   cls


:COPYDONE

   cls
   color 4F

   Echo.
   Echo.
   Echo 	ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
   Echo 	º                                                              º
   Echo 	º         YOU MUST REBOOT THE COMPUTER AND RERUN THIS          º
   Echo 	º                                                              º
   Echo 	º          BATCH FILE! YOUR PROGRESS HAS BEEN SAVED            º
   Echo 	º                                                              º
   Echo 	º         PRESS ANY KEY TO RESTART THE COMPUTER NOW!           º
   Echo 	º                                                              º
   Echo 	ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
   Echo.
   Echo.

   Pause

   del "C:\Install Logs\ReBoot.Needed.log"

   shutdown -t 0 -r -f

Exit



REM ---------------------------------------------------------------------------------------------------------------------------------



:ERROR

if exist "%tmp%\tmp1.vbs" ( del "%tmp%\tmp1.vbs" )
if exist "%tmp%\tmp2.vbs" ( del "%tmp%\tmp2.vbs" )
if exist "%tmp%\tmp3.vbs" ( del "%tmp%\tmp3.vbs" )

cls
echo.
echo An unexpected error has occured. Please contact your administrator.
msg %username% /w An error has occured. Please contact your administrator for further assistance.

if "%~f0" == "%userprofile%\AppData\Roaming\MICROS~1\Windows\STARTM~1\Programs\Startup\%~nx0" ( goto :CLEANUP )

Exit



REM ---------------------------------------------------------------------------------------------------------------------------------



:progress
SETLOCAL ENABLEDELAYEDEXPANSION
SET ProgressPercent=%1
SET /A NumBars=%ProgressPercent%/2
SET /A NumSpaces=50-%NumBars%
SET Meter=
FOR /L %%A IN (%NumBars%,-1,1) DO SET Meter=!Meter!I
FOR /L %%A IN (%NumSpaces%,-1,1) DO SET Meter=!Meter! 
TITLE Progress:  [%Meter%]  %ProgressPercent%%%
ENDLOCAL
 

My Computer My Computer

Computer type
PC/Desktop
OS
Windows 7 Pro x64 / Windows 8.1 Pro x64
Thank you for yours :)
 

My Computer My Computer

Computer type
PC/Desktop
Computer Manufacturer/Model Number
Custom Built
OS
Windows 10 Pro
CPU
AMD Ryzen 5 2400G Processor with Radeon RX Vega 11 Graphics
Motherboard
ASRock X470 Master SLI/AC AM4 AMD Promontory X470 SATA 6Gb/s
Memory
G.SKILL Ripjaws V Series 16GB (2 x 8GB) 288-Pin DDR4 SDRAM D
Graphics Card(s)
2047MB NVIDIA GeForce GTX 1060 6GB (EVGA)
Sound Card
Motherboard Built in
Monitor(s) Displays
Acer R240HY bidx 23.8-Inch IPS HDMI DVI VGA (1920 x 1080) Wi
Screen Resolution
1920 x 1080
Hard Drives
1TB Sandisk SSD PLUS (Main drive)
500 GB Seagate 7200 RPM (Games)
500 GB Western Digital 7200 RPM (Virtual Machines)
PSU
CORSAIR TX Series TX650M 650W 80+ Gold Modular Power Supply
Case
CORSAIR CARBIDE SPEC-02 Mid-Tower Gaming Case, Red LED Fan
Cooling
220mm, two 120mm, and four 60mm fans
Keyboard
Wired Dell keyboard
Mouse
Wireless Logitech mouse
Internet Speed
250mb down, 30mb up
Antivirus
Panda Cloud Antivirus
Browser
Chrome-ish x64
Other Info
Your awesome for reading this.
Back
Top