cmd - How do you run a command as an administrator from ...
文章推薦指數: 80 %
All you have to do is use the runas command to run your program as Administrator (with a caveat) ...
Lastcalltomakeyourvoiceheard!Our2022DeveloperSurveyclosesinlessthanaweek.Takesurvey.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
HowdoyourunacommandasanadministratorfromtheWindowscommandline?
AskQuestion
Asked
11yearsago
Modified
7daysago
Viewed
349ktimes
77
46
IhaveasmallscriptthatperformsthebuildandinstallprocessonWindowsforaBazaarrepositoryI'mmanaging.I'mtryingtorunthescriptwithelevated,administrativeprivilegesfromwithintheWindowsshell(cmd.exe)--justasifI'dright-clickeditandchosenRunasAdministrator,butwithoutusinganymethodthatrequiresuseofthegraphicalinterface.
cmdwindows-7windows-vista
Share
Follow
editedDec11,2017at18:11
PeterMortensen
30k2121goldbadges100100silverbadges124124bronzebadges
askedMay10,2011at1:13
jpaughjpaugh
6,11744goldbadges3636silverbadges8787bronzebadges
2
1
Toruncommandsasadmin,I'vemadeasudo-liketoolforWindows,availableasaChocolateypackage:stackoverflow.com/a/54642324/1768303
– noseratio
Feb13,2019at21:55
1
@noseratioWhileyourcommentisn'tinthespiritofthequestion,itlookslikeaconvenienttool.
– jpaugh
Feb13,2019at23:01
Addacomment
|
12Answers
12
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
69
Pressthestartbutton.Inthesearchboxtype"cmd",thenpressCtrl+Shift+Enter
Share
Follow
editedOct23,2015at7:02
ROMANIA_engineer
51.2k2626goldbadges196196silverbadges185185bronzebadges
answeredAug19,2013at14:43
slashdottirslashdottir
7,25977goldbadges5050silverbadges6969bronzebadges
2
15
notwhattheopquestioned,butanyway-goodtoknowthisshortcut!-thanks
– eXe
Jul22,2015at8:56
Thisdoesnotattempttoanswerthequestionasasked,andreallyshouldn'tbethehighestratedanswer.-1
– James
Feb2at0:15
Addacomment
|
67
AllyouhavetodoisusetherunascommandtorunyourprogramasAdministrator(withacaveat).
runas/user:Administrator"cmdNameparameters"
Inmycase,thiswas
runas/user:Administrator"cmd.exe/C%CD%\installer.cmd%CD%"
NotethatyoumustuseQuotationmarks,elsetherunascommandwillgobbleuptheswitchoptiontocmd.
Alsonotethattheadministrativeshell(cmd.exe)startsupintheC:\Windows\System32folder.Thisisn'twhatIwanted,butitwaseasyenoughtopassinthecurrentpathtomyinstaller,andtoreferenceitusinganabsolutepath.
Caveat:Enabletheadminaccount
Usingrunasthiswayrequirestheadministrativeaccounttobeenabled,whichisnotthedefaultonWindows7orVista.However,hereisagreattutorialonhowtoenableit,inthreedifferentways:
ImyselfenableditbyopeningAdministrativeTools,LocalSecurityPolicy,thennavigatingtoLocalPolicies\SecurityOptionsandchangingthevalueoftheAccounts:AdministrativeAccountStatuspolicytoEnabled,whichisnoneofthethreewaysshowninthelink.
Aneveneasierwaytoaccomplishthis:
C:>netuserAdministrator/active:yes
Share
Follow
editedDec14,2021at16:06
mohkamfer
39722silverbadges1212bronzebadges
answeredMay10,2011at17:29
jpaughjpaugh
6,11744goldbadges3636silverbadges8787bronzebadges
4
3
Isthereawaytorunasadifferentuser(thathasadminrights)insteadofastheAdministator?Thisisprettyimportantforuswithworkcomputers...
– Urchin
Apr15,2015at18:30
Iimagineso.Tryit,andseeifitworks.But,IDKwhichspecificpermissionstheuserwouldneedinordertorunaparticularcommand,ortogain"adminstatus"ingeneral.
– jpaugh
Apr16,2015at20:06
1
Thisworks,butit'snotcompletelylinuxlike.Ihavenoticedhiccupsduringit'suse.Alsoatfirstthereisroughlya5secpausebeforethecommandisexecuted.Useitatyourowndiscretion.
– KeyC0de
Jan31,2017at18:57
You'rerightabouthiccups!Someprogramswillnotrunwithelevatedprivilegesunlesstheshell(explorer.exe)isalsorunningasanadminuser.(E.g:control.exe.)However,formyoriginalpurpose(seamlessinstallation),Ander'sanswerismuchbettersuited.
– jpaugh
Jan31,2017at19:26
Addacomment
|
50
+50
Abatch/WSHhybridisabletocallShellExecutetodisplaytheUACelevationdialog...
@if(1==1)@if(1==0)@ELSE
@echooff&SETLOCALENABLEEXTENSIONS
>nul2>&1"%SYSTEMROOT%\system32\cacls.exe""%SYSTEMROOT%\system32\config\system"||(
cscript//E:JScript//nologo"%~f0"
@goto:EOF
)
echo.Performingadmintasks...
REMcallfoo.exe
@goto:EOF
@end@ELSE
ShA=newActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c\""+WScript.ScriptFullName+"\"","","runas",5);
@end
Share
Follow
answeredMay11,2011at19:47
AndersAnders
90.1k1212goldbadges105105silverbadges156156bronzebadges
13
1
Couldyouplease,@Anders,tellmewhataretherequirementsforthisscripttowork?a)Windowsversion,b)VisualBasicor.NETinstalled,c)Javainstalled.InaplainsightitseemstometherearenonebutjustaWindowsrunning,butIamnotsure.Thanks.
– SopalajodeArrierez
Mar21,2014at14:15
2
@SopalajodeArrierez:TherunasverbwasaddedinWin2000andcscript.exewasaddedinWin98/IE4IIRC.
– Anders
Mar21,2014at19:55
Thanks,@Anders.Please,aminorquestion:Iamtryingtouseyourscriptwithmyownprogram(callinga.lnkfilethatexecutesaWindowsshell.exe),andIcannotsetmypreferredicon,asIalwaysdowithany.lnkfile.Thisis:theicongetsassignedtothe.lnk,butduringtheexecution(afteracceptingUACprompt)therunningwindowhastheusualCMDicon.Isthereawaytosolvethis?
– SopalajodeArrierez
Mar22,2014at12:35
1
ShellExecuteisaWindowsAPIfunction(msdn.microsoft.com/en-us/library/windows/desktop/bb762153)andbyusingthe"runas"verbwerequestUACelevationtostartcmd.exethatwillexecuteourscriptagainbutthissecondtimeitshouldbeelevated...
– Anders
Sep17,2014at11:00
2
The@prefixinbatchfilesturnsoffecho'ingofthatcommandand@istheprefixusedfor"pre-processor"instructionsinWindowsScriptingHost(msdn.microsoft.com/en-us/library/58dz2w55).@if(1==1)islegalsyntaxinbothbatchandWSHandtherestistheretomakethescriptexecutesthebatchorWSHcodedependingonwhichscriptprocessorisactuallyrunning.(BatchfilecallsWSH(ifrequiredinthiscase)thatcallsbatchfileagain,the2ndtimeafterbeingexecutedwithaspecialverb)
– Anders
Oct7,2014at0:15
|
Show8morecomments
17
::-------Self-elevating.bat--------------------------------------
@whoami/groups|find"S-1-16-12288">nul&&goto:admin
set"ELEVATE_CMDLINE=cd/d"%~dp0"&call"%~f0"%*"
findstr"^:::""%~sf0">temp.vbs
cscript//nologotemp.vbs&deltemp.vbs&exit/b
:::SetobjShell=CreateObject("Shell.Application")
:::SetobjWshShell=WScript.CreateObject("WScript.Shell")
:::SetobjWshProcessEnv=objWshShell.Environment("PROCESS")
:::strCommandLine=Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
:::objShell.ShellExecute"cmd","/c"&strCommandLine,"","runas"
:admin-------------------------------------------------------------
@echooff
echoRunningaselevateduser.
echoScriptfile:%~f0
echoArguments:%*
echoWorkingdir:%cd%
echo.
::administratorcommandshere
::e.g.,runshellasadmin
cmd/k
Forademo:self-elevating.bat"pathwithspaces"arg234"anotherlongargument"
Andthisisanotherversionthatdoesnotrequirecreatingatempfile.
延伸文章資訊
- 1一點通- Windows 7 啟用系統管理員Administrator 帳戶(MVP 撰寫)
出現[使用者帳戶控制] 對話視窗,點選[是]。 出現以系統管理員身分執行的[命令提示字元],輸入net user administrator / ...
- 2How to Run Command Prompt as an Administrator in ...
You can use the keyboard shortcut to force Command Prompt to run as administrator. For that, you ...
- 3如何以系統管理員身分執行命令提示字元? - Trend Micro Help ...
請在下方的搜尋欄位輸入「CMD」。 3. 對搜尋結果的CMD應用程式點選滑鼠右鍵。(如圖1.) 4. 再點選「以系統管理員身分執行(A)」。(如圖2.) For Windows 8.1 作業系統.
- 4Windows 7: Opening the Command Prompt as Administrator
Open the Command Prompt with Administrative Privileges · 1. Click the Start icon and click in the...
- 5如何在CMD下運用管理員權限 - 程式人生
方法一:鼠標右鍵這個方法比較比較普通, 點開開始找到cmd,右擊鼠標“以 ... runas /user:administrator cmd 但是這裏你得知道administrator的密碼。