Windows 7 Forums

Welcome to Windows 7 Forums. Our forum is dedicated to helping you find support and solutions for any problems regarding your Windows 7 PC be it Dell, HP, Acer, Asus or a custom build. We also provide an extensive Windows 7 tutorial section that covers a wide range of tips and tricks.


Windows 7: Batch File on USB fails when Ran As Administrator

08 Aug 2014   #1
JaoJack

Windows 7 Pro x64 / Windows 8.1 Pro x64
 
 
Batch File on USB fails when Ran As Administrator

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 System SpecsSystem Spec
.
08 Aug 2014   #2
JaoJack

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 System SpecsSystem Spec
10 Aug 2014   #3
andrew129260

Windows 10 Pro
 
 

Quote   Quote: Originally Posted by JaoJack View Post
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 System SpecsSystem Spec
.

11 Aug 2014   #4
JaoJack

Windows 7 Pro x64 / Windows 8.1 Pro x64
 
 

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 System SpecsSystem Spec
11 Aug 2014   #5
andrew129260

Windows 10 Pro
 
 

Thank you for yours
My System SpecsSystem Spec
Reply

 Batch File on USB fails when Ran As Administrator




Thread Tools Search this Thread
Search this Thread:

Advanced Search




Similar help and support threads
Thread Forum
Execute Program in Batch File As Administrator (Or Other Solution)
We use a program called TFC.exe (Temp File Cleaner - addpcs.com) to wipe all sorts of temp files off a computer on a monthly basis. The older version was a standalone .exe that users used to execute from a a folder on a server. The newer version is actually installed on each user's PC. If...
General Discussion
shutdown in batch file requires Administrator
Hi all, I've been using GFI Backup 2009 for backups for a while, it does everything I want, and sends email reports after backup is complete. One of its features is to shutdown the computer after a backup, this rarley works, as it wont shutdown if a program is already running, including GFI...
General Discussion
How to run a batch file at logoff & some batch scripting help please
Hiya, I'd just like to run a simple batch file at logoff to backup some settings. I plan to use Robocopy, which is what i use to more thorough backups. Two questions: 1. How make it run by clicking Start > Shutdown? (i realise i could make a shutdown batch file and run it instead, but i'd...
Backup and Restore
Batch file to stop services fails
Back in the good ol days of xp when I wanted to take my machine off the net and use it for music production I had a seperate hardware profile setup with lots of services (including all the networking ones) disabled. With vista I discovered microsoft had taken this ablity away. So I wrote a batch...
Performance & Maintenance
Batch File that grabs file names from folder to insert into batch file
Ok I'm totally at a loss on how to word this so I'm just going to write it out the best that I can... :confused: First I have a batch file that I'm writing that will convert mp4 files to mp3 files (I have a lot) for a buddies band using ffmpeg. Here's the code that I'm using: ffmpeg -i...
General Discussion
How to always run batch file as administrator?
I've made a batch file, but i don't know how to make it to always run as administartor. In .bat's file properties the option "always run as administartor" is grayed out. I have to right click it and then choose "run as administartor" from context menu. But i don't want to do it every time because...
General Discussion


Our Sites

Site Links

About Us

Find Us

Windows 7 Forums is an independent web site and has not been authorized, sponsored, or otherwise approved by Microsoft Corporation. "Windows 7" and related materials are trademarks of Microsoft Corp.

ฉ Designer Media Ltd

All times are GMT -5. The time now is 05:06.

Twitter Facebook Google+



Windows 7 Forums

Seven Forums Android App Seven Forums IOS App