Question

I work for a company where I've developed a batch script which needs to be enabled or disabled at times. I have my main batch file which executes a long process and then two other files to enable or disable it. Both work fine in Windows XP but in Windows 7 when I want to disable the task in task scheduler the cmd prompt comes up and gives me an access denied error. However, this does work successfully if I right click and run as administrator.

Well, this is meant to be an automated process so no one is going to be there to do the right click option and this is being deployed for a large scale of people. So, is there something I can put at the top of the batch script, that will cause a .bat to run as administrator by default?

Was it helpful?

Solution

This script too works for you! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.

@echo off

:: 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"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

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

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

<YOUR BATCH SCRIPT HERE>

OTHER TIPS

Force a batch to run as different user via RunAs command. This snippet checks the USERNAME environment variable. If it is not Administrator then it automatically restart the batch with Administrator credentials using the RunAs command. Administrator password is required.

@echo off
echo.Current User is '%USERNAME%'

rem -- Let's make sure this batch runs as Administrator --
set "RunAsUser=Administrator"
if "%USERNAME%" NEQ "%RunAsUser%" (
    RUNAS /user:%RunAsUser% "cmd /c %~f0"||PAUSE
    GOTO:EOF
)

rem -- your code goes below here --
echo.Hello World

ECHO.&PAUSE&GOTO:EOF
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top