如何为AutoHotkey脚本添加管理员权限?

bar*_*k56 5 autohotkey administrator

我将其编译为可执行文件,但要打开它,我必须右键单击并按"以管理员身份运行".我想让它在每次运行时请求管理员权限,但是怎么做呢?

我不能这样做:

因为当我将它复制到第二台计算机时它不起作用.

use*_*297 13

尝试将其添加到自动执行部分(脚本顶部):

; If the script is not elevated, relaunch as administrator and kill current instance:

full_command_line := DllCall("GetCommandLine", "str")

if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try ; leads to having the script re-launching itself as administrator
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}
Run Code Online (Sandbox Code Playgroud)

并重新编译脚本.

有关详细信息,请阅读https://autohotkey.com/docs/commands/Run.htm#RunAs.


Sha*_*yan 6

这是用于此目的的更简单的代码:

#SingleInstance Force

if not A_IsAdmin

  Run *RunAs "%A_ScriptFullPath%"
Run Code Online (Sandbox Code Playgroud)

如果脚本尚未以管理员身份运行,它将以管理员身份运行该脚本。

如果你没有#SingleInstance Forceon top of 你的脚本,它会询问你是否想用 admin 替换正在运行的脚本(不是 admin)。因此,为了防止这种情况,请将提到的行添加到脚本顶部。

如果您将来可能编译脚本,最好使用这个脚本以使其面向未来:

#SingleInstance Force

if !A_IsAdmin
    Run, % "*RunAs " (A_IsCompiled ? "" : A_AhkPath " ") Chr(34) A_ScriptFullPath Chr(34)
Run Code Online (Sandbox Code Playgroud)

Chr(34)返回字符"

来源: https: //www.autohotkey.com/boards/viewtopic.php ?t=39647