Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have created a batch file for starting a service using sc.exe. But it asks for admin privilege while running. Is there is any code that can be used in batch file to elevate cmd to admin level?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this:

@echo off
>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"
if %errorlevel% NEQ 0 (GOTO askAdmin)
GOTO gotAdmin


:askAdmin
::batch is being ran as normal user
echo I'm not an admin yet
>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"
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"
::batch is being ran as admin
echo Now I'm an admin!
pause

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...