Windows – Batch file with commands to run as administrator and standard user

batch filecommand linewindows

I'm trying writing a batch file that needs to run some commands using a local admin account (start/stop a service) and some commands using the logged in user (copy files from the user directory) and I'm encountering problems. I have tried the following commands:

runas with /savecred

runas /user:(PC name)\(admin username) /savecred "net stop \"(service name)\""
runas /user:(PC name)\(admin username) /savecred "sc stop \"(service name)\""

When using /savecred I am not prompted for a password. Instead a command prompt window briefly flashes up and disappears. I am not able to tell what is in this window. The service is not stopped.

runas without /savecred

runas /user:(PC name)\(admin username) "net stop \"(service name)\""
runas /user:(PC name)\(admin username) "sc stop \"(service name)\""

These commands do prompt me for a password but then exhibit the same behaviour as the above commands – a command prompt window briefly pops up and the service is not stopped.

Ideally I would like to save the password for the session as I will need to run more commands with the details.

Is this possible and if so, what am I doing wrong?

Best Answer

You can add the following to your script and it will force it to run elevated. No need to download anything.

:: 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"
:--------------------------------------