我有一个使用 cscript.exe
运行的 JScript 脚本。它在桌面(以及开始菜单)上创建一个快捷方式,该快捷方式运行带有参数的 cscript.exe
以运行另一个 JScript 脚本。在相关部分,它看起来像这样:
function create_shortcut_at(folder, target_script_folder)
{
var shell = new ActiveXObject("WScript.Shell");
var shortcut = shell.CreateShortcut(folder + "\\Run The Script.lnk");
shortcut.TargetPath = "cscript";
shortcut.Arguments = "\""+target_script_folder+"\\script.js\" /aParam /orTwo";
shortcut.IconLocation = target_script_folder+"\\icon.ico";
shortcut.Save();
}
它的调用方式类似于create_shortcut_at(desktop_folder, script_folder)
。
就目前而言,这是有效的。它创建桌面图标,正确指向脚本并在双击时运行它。问题是它确实需要“以管理员身份”运行脚本。
该脚本确实需要“以管理员身份”运行——它会(为所有用户)安装应用程序并重新启动计算机。 (有兴趣的人,脚本是wpkg.js,修改为自提升是不可取的。)
由于快捷方式的目标实际上是“cscript.exe”,因此我无法使用 list 进行升级。理论上我可以在 Windows 目录中安装 cscript.exe.manifest,但即使有效,出于显而易见的原因,这也是一个糟糕的主意。
我也不想使用虚拟脚本,因为这是一个需要处理的额外文件,并且手头还有另一个看似合理的解决方案:选中快捷方式上的“以管理员身份运行”框。
三十秒的调查显示 WScript.Shell ActiveX 对象不具备此操作所需的接口(interface)。额外的调查表明 IShellLinkDataList 确实如此。然而,IShellLinkDataList 是一个通用的 COM 接口(interface)。我在互联网上看到了几个例子,大多数链接为 here 。但是,所有示例都是在编译代码(C++、C#,甚至 JScript.NET)中执行的。我非常喜欢能够直接在 JScript 中执行此操作,从 cscript.exe
运行。
也就是说,我完全支持我没有考虑过的想法或其他解决方案。
最佳答案
将快捷方式文件标记为需要提升的官方方法是通过 IShellLinkDataList
。从自动化环境中使用该界面很困难。
但是,如果您对 hack 感到满意,您可以在脚本中完成它,只需在 .lnk 文件中翻转一点即可。
当您在“Shell 属性”框的“高级”选项卡中勾选“以管理员身份运行”框时,或者当您 use IShellLinkDataList to set the flags包括SLDF_RUNAS_USER
,您基本上只是在文件中设置一位。
您可以“手动”执行此操作,而无需通过 COM 接口(interface)。它是字节 21,您需要将 0x20 位设置为打开。
(function(globalScope) {
'use strict';
var fso = new ActiveXObject("Scripting.FileSystemObject"),
path = "c:\\path\\goes\\here\\Shortcut2.lnk",
shortPath = path.split('\\').pop(),
newPath = "new-" + shortPath;
function readAllBytes(path) {
var ts = fso.OpenTextFile(path, 1), a = [];
while (!ts.AtEndOfStream)
a.push(ts.Read(1).charCodeAt(0));
ts.Close();
return a;
}
function writeBytes(path, data) {
var ts = fso.CreateTextFile(path, true),
i=0, L = data.length;
for (; i<L; i++) {
ts.Write(String.fromCharCode(data[i]));
}
ts.Close();
}
function makeLnkRunAs(path, newPath) {
var a = readAllBytes(path);
a[0x15] |= 0x20; // flip the bit.
writeBytes(newPath, a);
}
makeLnkRunAs(path, newPath);
}(this));
ps:
function createShortcut(targetFolder, sourceFolder){
var shell = new ActiveXObject("WScript.Shell"),
shortcut = shell.CreateShortcut(targetFolder + "\\Run The Script.lnk"),
fso = new ActiveXObject("Scripting.FileSystemObject"),
windir = fso.GetSpecialFolder(specialFolders.windowsFolder);
shortcut.TargetPath = fso.BuildPath(windir,"system32\\cscript.exe");
shortcut.Arguments = "\"" + sourceFolder + "\\script.js\" /aParam /orTwo";
shortcut.IconLocation = sourceFolder + "\\icon.ico";
shortcut.Save();
}
关于com - 如何使用 JScript 创建使用 "Run as Administrator"的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11162802/