在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
很多时候我们需要管理员权限来运行bat那么就需要结合vbscript来实现了 方法一: %1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit 常用 @echo off mode con lines=30 cols=60 %1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit cd /d "%~dp0" rem 下面可以写你的bat代码了 方法二: @echo off %1 %2 ver|find "5.">nul&&goto :st mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :st","","runas",1)(window.close)&goto :eof :st copy "%~0" "%windir%\system32\" 原理类似 ShellExecute method Run a script or application in the Windows Shell. Syntax .ShellExecute 'some program.exe', '"some parameters with spaces"', , "runas", 1 The runas verb is undocumented but can be used to elevate permissions. When a script is run with elevated permissions several aspects of the user environment may change: The current directory, the current TEMP folder and any mapped drives will be disconnected. runas will fail if you are running in WOW64 (a 32 bit process on 64 bit windows) for example %systemroot%\syswow64\cmd.exe ... The ShellExecute method is a member of the IShellDispatch2 object. Examples Run a batch script with elevated permissions, flag=runas: Set objShell = CreateObject("Shell.Application") objShell.ShellExecute "E:\demo\batchScript.cmd", "", "", "runas", 1 Run a VBScript with elevated permissions, flag=runas: Set objShell = CreateObject("Shell.Application") objShell.ShellExecute "cscript", "E:\demo\vbscript.vbs", "", "runas", 1 “If you don't execute your ideas, they die” ~ Roger Von Oech Related: Run with elevated permissions - Script to run as Admin 批处理文件中的%~dp0表示含义 ~是扩展的意思,相当于把一个相对路径转换绝对路径
自从Vista带来了UAC之后,应用程序就变成了两种,有管理员权限的,和没有管理员权限的。一些老的应用程序会莫名其妙地出错,这时候就要考虑右击应用程序,然后“以管理员身份运行”。这还不是什么大问题,exe文件的右键菜单里都会有这个,但是对于一些脚本文件(cmd, js一类)来说,就没那么方便了。通常需要重新开一个带管理员权限的命令行窗口,然后打很多cd回到刚的文件夹,然后再运行脚本,相当麻烦。 搜了一下,找到一个解决办法。把下面的代码保存为Elevate.js: var command = WScript.Arguments.Item(0); var argument = ""; for (var i = 0; i < WScript.Arguments.Count(); ++i){ argument += WScript.Arguments.Item(i) + " "; } try{ var shellapp = new ActiveXObject("Shell.Application"); shellapp.ShellExecute(command, argument, null, "runas", 1); } catch(e){ WScript.Echo("Something wrong: " + e.description); } 以后要以管理员身份运行程序的时候,只要输入“Elevate <exefile> <arguments>”就可以了,比如“Elevate cmd /k”。 当然,这个逃不过UAC的检查,还是会有一个对话框弹出来要点“确定”的。 |
请发表评论