user3016723
user3016723

Reputation: 11

Run BAT as admin (w/o shortcut)

So, I am trying to create a .bat to taskkill a specific program in Win7.

I am using the command:

taskkill /f /im "LCore.exe"

The .bat needs to be run as admin in order to work it seems so I have created a shortcut to it to run automatically in admin mode as specified in another thread (How to code a BAT file to always run as admin mode?).

However, when using the Microsoft Mouse and Keyboard Center to map one of my additional keys to run the shortcut it automatically runs the target of the shortcut rather than the shortcut itself which doesn't have the admin privileges needed (when selecting to map the shortcut it automatically changes the path to the target, manually setting the path returns a 'not found' error).

So basically I was wondering if there is another way that doesn't involve creating a shortcut to automatically run a .bat with elevated privileges.

Upvotes: 1

Views: 2955

Answers (2)

Artem Zaytsev
Artem Zaytsev

Reputation: 11

In Windows 7 you don't need to write additional scripts, because it has built-in "PowerShell" instrument. Try the following :

powershell.exe start-process taskkill.exe -verb runas -argumentlist '/f /im "LCore.exe"'

Upvotes: 1

user3018347
user3018347

Reputation: 33

@ECHO OFF

OPENFILES>NUL 2>&1
IF "%ERRORLEVEL%"=="0" GOTO :YouAreAdmin
GOTO :GetAdmin

:GetAdmin
ECHO.Set UAC = CreateObject^("Shell.Application"^) > "StartAsAdmin.vbs"
ECHO.UAC.ShellExecute "%~fs0", "", "", "runas", 1 >> "StartAsAdmin.vbs"
StartAsAdmin.vbs
DEL "StartAsAdmin.vbs"
EXIT /B

:OK
REM Your code starts here!
ECHO.
ECHO. If you see this, you have started as admin this bat file.
PAUSE>NUL
EXIT

Sorry, but I am new! :)

So first, OPENFILES command checks if you have runned program as administrator, like any command that needs administrator privileges. If you type >NUL 2>&1 after a command, CMD will hide any message from that command and will redirect error. So if you have troubles running a simple command action like OPENFILES, the only error that you can have is that batch file doesen't have administrator privileges. And if %ErrorLevel% is 0 (you have no errors running that command), it seems that you started application as administrator, so it steps to :OK label. But if %ErrorLevel% is not 0 (there is a problem), it seems that application doesen't have administrator privileges. So it will start automatly as administrator from a temporary VBScript generated by that batch file, then is started, and then deleted.

Upvotes: 2

Related Questions