cmd - How do you run a command as an administrator from ...

文章推薦指數: 80 %
投票人數:10人

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. 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 Share Follow editedNov23,2014at9:15 answeredNov22,2014at23:31 AmrAliAmrAli 2,21211goldbadge1515silverbadges1111bronzebadges 4 Thesecondversionisreallyamazing.Lookatthatbeautifycscript"self-elevating.bat?.wsf"part. – Rockallite Apr29,2015at2:01 1 Theplain-text.batandXML.wshmix-incontentisalsogorgeous. – Rockallite Apr29,2015at2:16 WhatistheSIDfromfind"S-1-16-12288"?ItdoesnotappearwhenIusewhoami/groups. – lit Sep16,2015at14:34 That'sverycool.IwouldchangetheELEVATE_CMDLINEtocdto%cd%insteadsothatrelativepathsintheinitialinvocationarecorrect. – sgraham Aug29,2016at17:32 Addacomment  |  4 Although@amrali'scodewasgreat,Ihadaninstancewheremybatfilecontained>Checkforpermissions >nul2>&1"%SYSTEMROOT%\system32\cacls.exe""%SYSTEMROOT%\system32\config\system" REM-->Iferrorflagset,wedonothaveadmin. if'%errorlevel%'NEQ'0'( echoRequestingadministrativeprivileges... gotoUACPrompt )else(gotogotAdmin) :UACPrompt echoSetUAC=CreateObject^("Shell.Application"^)>"%temp%\getadmin.vbs" echoUAC.ShellExecute"%~s0","","","runas",1>>"%temp%\getadmin.vbs" "%temp%\getadmin.vbs" exit/B :gotAdmin ifexist"%temp%\getadmin.vbs"(del"%temp%\getadmin.vbs") pushd"%CD%" CD/D"%~dp0" :-------------------------------------- Share Follow editedDec11,2017at18:16 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredMay3,2017at3:27 KapantherKapanther 4122bronzebadges 0 Addacomment  |  2 Iwouldsetupashortcut,eithertoCMDortothethingyouwanttorun,thensetthepropertiesoftheshortcuttorequireadmin,andthenruntheshortcutfromyourbatchfile.Ihaven'ttestedtoconfirmitwillrespecttheproperties,butIthinkit'smoreelegantanddoesn'trequireactivatingtheAdministratoraccount. Alsoifyoudoitasascheduledtask(whichcanbesetupfromcode)thereisanoptiontorunitelevatedthere. Share Follow answeredMay11,2011at13:12 KateGregoryKateGregory 18.6k88goldbadges5555silverbadges8585bronzebadges 2 1 Well,mygoalmastodoitcompletelyfromthecommandline.Ican'texpecteveryonewhousesmyinstallertofollowthisprocessbeforerunningmyinstaller. – jpaugh May11,2011at14:29 @Kate-Iactuallyhadthesameideaasyouandwastryingthistodayonawin2012server,butunfortunately,itdoesnotwork.Thecommandpromptstillrunswithoutadminrightsevenifyousettheshortcutupas"runasadministrator".ThisiswhenItrytousetheshortcutviaTaskScheduler.TaskSchedulermustdosomethingunderthecoverstopreventitfromrunningasadmin,I'mnotsure. – dcp Jul25,2014at14:55 Addacomment  |  2 Simplepipetrick,||,withsome.vbsusedattopofyourbatch.Itwillexitregularandrestartasadministrator. @AT>NUL||echosetshell=CreateObject("Shell.Application"):shell.ShellExecute"%~dpnx0",,"%CD%","runas",1:setshell=nothing>%~n0.vbs&start%~n0.vbs/realtime&timeout1/NOBREAK>nul&del/Q%~n0.vbs&cls&exit Italsodel/Qthetemp.vbswhenit'sdoneusingit. Share Follow editedDec11,2017at18:15 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredDec30,2014at7:07 strancestrance 4733bronzebadges 1 3 Thisiswicked!Wouldyoumindexplainingthatlineabitmoreindepth? – jpaugh Dec31,2014at15:14 Addacomment  |  0 BrowsetoC:\windows\System32andrightclickoncmd.exeandrunasAdministrator.WorkedformeonWindows7. Ifyouaretryingtorunascriptwithelevatedprivilegesyoucoulddothesameforthescriptfileorusethescheduler'srunasadifferentuseroptiontorunthescript. Share Follow answeredMay10,2011at1:31 RasikaRasika 1,9921313silverbadges1919bronzebadges 1 Thisisgreat,butnotsomethingIcoulddofromwithinthecommandline,e.g.,fromaninstallscript.Theonlyuserinterventionthatshouldberequiredisconfirmingtheelevation--similartowhenyouinstallanyprogramonWindows6/7. – jpaugh May10,2011at17:31 Addacomment  |  0 ijustcreatedanshortcutinmydesktopwiththislineintarget: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe-commandStart-Process-verbRunAswt andafterpinnedintaskbar:) Share Follow answeredMay17,2021at15:37 RenanDuarteRenanDuarte 8311silverbadge99bronzebadges 1 Theshortcutisbothunnecessaryandunusableinthecontextoftheoriginalquestion,whichwasaboutmakinganinstallertorunonanend-user'ssystem.However,thecommandisinteresting.Itlookslikethisisasimplificationoftheacceptedanswer.Isthatcorrect?DoesitbringuptheUACdialog? – jpaugh May17,2021at18:09 Addacomment  |  0 NirCmdwww.nirsoft.netofferselevated Usenircmdc Share Follow answeredFeb21at18:14 AngelicCAngelicC 4133bronzebadges Addacomment  |  0 YoucancallPowerShellviaitsCLI,powershell.exe,inordertocallitsStart-Processcmdlet,whichsupportsstartingprocesseswithelevation;doingsohastwoadvantages: Youdon'tneedahybridbatchfilethatusesclever,butobscuretrickstocombinethelanguagesoftwodistinctenvironmentsinasinglefile. Youmayplace-Waitbefore-VerbRunAs(seebelow)inordertomaketheelevatedreinvocationsynchronous,i.e.towaitforittoexitandcommunicateitsexitcodetothecaller. ThefollowingborrowstechniquesfromAmrAli'shelpfulWSH-assistedanswer;saveandrunasrun-elevated.cmd,forinstance: @echooff&setlocal ::Checkifthecurrentsessionisalreadyelevated. ::`netsession`onlysucceedsinelevatedsessions. netsession>NUL2>&1&&goto:ELEVATED ::Gettingheremeansthatwemustreinvokewithelevation. ::Add-Waitbefore-VerbRunAstowaitforthereinvocationtoexit. setELEVATE_CMDLINE=cd/d"%~dp0"^&"%~f0"%* powershell.exe-noprofile-cStart-Process-VerbRunAscmd.exe\"/k$env:ELEVATE_CMDLINE\" exit/b%ERRORLEVEL% ::Gettingheremeansthatweare(now)runningwithelevation. :ELEVATED echo===Runninginelevatedsession: echoScriptfile:%~f0 echoArguments:%* echoWorkingdir:%cd% SpeakingofAmrAli'sWSH-assistedanswer;hereisareformulationthatmakespassingtheargumentsthroughmorerobust,sothatargumentssuchas"a&b"maybepassed,andpreventsduplicating"^"charactersinargumentsbyavoidingtheuseofcall-seelinesetELEVATE_CMDLINE=...;also,apartfromsomeformattingforreadability,itisensuredthatnoneoftheoriginalbatchstatementsareaccidentallyechoed: SetobjShell=CreateObject("Shell.Application") SetobjWshShell=WScript.CreateObject("WScript.Shell") SetobjWshProcessEnv=objWshShell.Environment("PROCESS") strCommandLine=Trim(objWshProcessEnv("ELEVATE_CMDLINE")) objShell.ShellExecute"cmd","/k"&strCommandLine,"","runas" :ELEVATED echo===Runninginelevatedsession: echoScriptfile:%~f0 echoArguments:%* echoWorkingdir:%cd% Share Follow answeredMay22at17:45 mklement0mklement0 311k5656goldbadges508508silverbadges621621bronzebadges Addacomment  |  -1 IpersonallydidnotsatisfiedwithanyofsuggestedsolutionssoItracedandfindouthowmicrosoftitselfisrunningsomecommandsasadministratorwithoutanyconfirmations. HereiswhatIfinallyfoundfromwindowsregistry: *RunAs"D:\Path\To\app.exe" *RunAs"D:\Path\To\app.exe"[YourCommandArgs] Share Follow answeredDec16,2021at21:20 MojtabaRezaeianMojtabaRezaeian 7,30577goldbadges2727silverbadges5050bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedcmdwindows-7windows-vistaoraskyourownquestion. TheOverflowBlog Gamesaregood,modsareimmortal(ep446) EthicalAIisn’tjusthowyoubuildit,itshowyouuseit FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication StagingGround:ReviewerMotivation,Scaling,andOpenQuestions CollectivesUpdate:IntroducingBulletins RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser The[social]tagisintheprocessofbeingburninated Linked 249 HowcanIauto-elevatemybatchfile,sothatitrequestsfromUACadministratorrightsifrequired? 168 Rootuser/sudoequivalentinCygwin? 143 Howtorun'sudo'commandinwindows 3 Notenoughpermissiontoruntypeperf.exe 0 Howtorunbatchscriptwithadminprivilegeprogrammatically? 0 HowdoIrunsomelinesinabatchscriptasadminbutothersasuser? -1 .batfilerunningcmdwithspecificcommandlines 0 customizationcommand-linebasedinstaller 0 Errorswheninstallinggulp-imagemin 0 HowtoopenMs-Worddocumentasadministratorbydefault? Seemorelinkedquestions Related 605 IsthereacommandtorefreshenvironmentvariablesfromthecommandpromptinWindows? 906 HowdoIgettheapplicationexitcodefromaWindowscommandline? 593 HowdoImeasureexecutiontimeofacommandontheWindowscommandline? 808 Howtorunmultiple.BATfileswithina.BATfile 582 HowcanIcreateanemptyfileatthecommandlineinWindows? 949 HowdoIforcemy.NETapplicationtorunasadministrator? 135 HowtodetectifCMDisrunningasAdministrator/haselevatedprivileges? 1209 HowdoIruntwocommandsinonelineinWindowsCMD? 1024 HowdoIkilltheprocesscurrentlyusingaportonlocalhostinWindows? HotNetworkQuestions Howtoputfiguresintolongtable IsparallelingMOSFETsagoodorbadidea? ParallelizerasterareacalculationperclassinR InvertaNon-commutativeFunction Isitsafetoconnecttwoaircompressorstogeathertoincreasetheairflowoutput? Do谢and写sounddifferent(ignoringthetones)? Tryingtotranslate:“BlessedbeGodwhocallsusHischildren.” DetermineUiltaPitchAccent Whataretherisksofleavingtoprintovernight? Whatislinguistics? Addahiddenlanguagetoapolyglot Howtoexplainbadgradesinphdapplicationduetobadlecturers? HowtocalculateMunicipalityfee,Servicecharge,andVATforrestaurantsinDubai Randombuzzing/humminginbottomcornerofLivingRoom…notelectric? Cryptocurrency:Whathappenstocoinvaluewhenitstransferedfromoneblockchainnetworktoother heaviertailsmeansthatitislesssensitivetooutlyingdataforlogisticandprobit Whatdoes'it'refertointhepassage? Mykitchenfaucetwasinstalledsothatthewaterdoesn'tflowintothecenterofthesink Isitpossibleforaprofessortowriteanegativeletterofrecommendation? Whycan'tnumbersbe'usedup'? DoesthisACtoDC+breadboardsetuphavetheabilitytokill/severelyhurtme? HowdoItellaprofessorIdon'tfindtheirresearchtopicinteresting? CanflakorsomeothermethodbeusedtodetonateWWI-styleartilleryshellsmid-air? HowdoesHebrews11:29sayitwasbyfaiththeycrossedtheredsea? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?