CMD命令行中以管理员权限启动应用程序实现方法
很多时候我们需要管理员权限来运行bat那么就需要结合vbscript来实现了
方法一:
%1mshtavbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c%~s0::","","runas",1)(window.close)&&exit
常用
@echooff modeconlines=30cols=60 %1mshtavbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c%~s0::","","runas",1)(window.close)&&exit cd/d"%~dp0" rem下面可以写你的bat代码了
方法二:
@echooff %1%2 ver|find"5.">nul&&goto:st mshtavbscript:createobject("shell.application").shellexecute("%~s0","goto:st","","runas",1)(window.close)&goto:eof :st copy"%~0""%windir%\system32\"
原理类似
ShellExecutemethod
RunascriptorapplicationintheWindowsShell.
Syntax
.ShellExecute"application","parameters","dir","verb",window
.ShellExecute'someprogram.exe','"someparameterswithspaces"',,"runas",1
Key
applicationThefiletoexecute(required)
parametersArgumentsfortheexecutable
dirWorkingdirectory
verbTheoperationtoexecute(runas/open/edit/print)
windowViewmodeapplicationwindow(normal=1,hide=0,2=Min,3=max,4=restore,5=current,7=min/inactive,10=default)
Notethedifferent(double"andsingle')quotesthatcanbeusedtodelimitpathswithspaces.
Therunasverbisundocumentedbutcanbeusedtoelevatepermissions.Whenascriptisrunwithelevatedpermissionsseveralaspectsoftheuserenvironmentmaychange:Thecurrentdirectory,thecurrentTEMPfolderandanymappeddriveswillbedisconnected.
runaswillfailifyouarerunninginWOW64(a32bitprocesson64bitwindows)forexample%systemroot%\syswow64\cmd.exe...
TheShellExecutemethodisamemberoftheIShellDispatch2object.
Examples
Runabatchscriptwithelevatedpermissions,flag=runas:
SetobjShell=CreateObject("Shell.Application") objShell.ShellExecute"E:\demo\batchScript.cmd","","","runas",1
RunaVBScriptwithelevatedpermissions,flag=runas:
SetobjShell=CreateObject("Shell.Application") objShell.ShellExecute"cscript","E:\demo\vbscript.vbs","","runas",1
“Ifyoudon'texecuteyourideas,theydie”~RogerVonOech
Related:
Runwithelevatedpermissions-ScripttorunasAdmin
.Exec-Executecommand,returninganobject
.Run-Runacommand
joeware.net-CPAU(CreateProcessAsUser)likeRunAsbutwithanoptionstoencryptthepassword.
EquivalentCMDcommand:ShellRunAs-Runacommandunderadifferentuseraccount
批处理文件中的%~dp0表示含义
~是扩展的意思,相当于把一个相对路径转换绝对路径
%0代指批处理文件自身
%1表示批处理文件命令行接收到的第一个参数,%2表示第二个,以此类推
%~d0是指批处理所在的盘符,其中d代表drive
%~p0是指批处理所在的目录,其中p代表path
%~dp0是批处理所在的盘符加路径
cd%~dp0就是进入批处理所在目录了
详细解释还可参考命令call/?
自从Vista带来了UAC之后,应用程序就变成了两种,有管理员权限的,和没有管理员权限的。一些老的应用程序会莫名其妙地出错,这时候就要考虑右击应用程序,然后“以管理员身份运行”。这还不是什么大问题,exe文件的右键菜单里都会有这个,但是对于一些脚本文件(cmd,js一类)来说,就没那么方便了。通常需要重新开一个带管理员权限的命令行窗口,然后打很多cd回到刚的文件夹,然后再运行脚本,相当麻烦。
搜了一下,找到一个解决办法。把下面的代码保存为Elevate.js:
varcommand=WScript.Arguments.Item(0); varargument=""; for(vari=0;i<WScript.Arguments.Count();++i){ argument+=WScript.Arguments.Item(i)+""; } try{ varshellapp=newActiveXObject("Shell.Application"); shellapp.ShellExecute(command,argument,null,"runas",1); } catch(e){ WScript.Echo("Somethingwrong:"+e.description); }
以后要以管理员身份运行程序的时候,只要输入“Elevate<exefile><arguments>”就可以了,比如“Elevatecmd/k”。
当然,这个逃不过UAC的检查,还是会有一个对话框弹出来要点“确定”的。