7

I compiled it to an executable, but to open it I have to right-click and press "Run as administrator". I want it to request admin privileges each time I run it, but how to do it?

I can't do this:

Because then it doesn't work when I copy it to a second computer.

Ooker
  • 1,969
  • 4
  • 28
  • 58
barteczek56
  • 95
  • 1
  • 1
  • 7

3 Answers3

17

Try adding this to the auto-execute section (top of the script):

; 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
}

and recompile the script.

For more details read https://autohotkey.com/docs/commands/Run.htm#RunAs.

user3419297
  • 9,537
  • 2
  • 15
  • 24
6

Here's a much simpler code for this purpose:

#SingleInstance Force

if not A_IsAdmin

  Run *RunAs "%A_ScriptFullPath%"

It will run the script as Admin if it's not already running as Admin.

If you don't have #SingleInstance Force on top of your script, it will ask that if you want to replace the running script (not admin) with admin. So to prevent that, add the mentioned line on top of your script.

If you might compile your script in the future, it's better to use this one instead to make it future-proof:

#SingleInstance Force

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

Chr(34) returns character "

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

Shayan
  • 709
  • 1
  • 15
  • 31
  • Doesn't work because `#SingleInstance Force` tries to kill the already-running script, but fails (because the running script is running as Admin, but the new invocation isn't) – snath03 May 26 '22 at 01:46
0

In AHK V2

#SingleInstance Force
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
  try
  {
    if A_IsCompiled
      Run '*RunAs "' A_ScriptFullPath '" /restart'
    else
      Run '*RunAs "' A_AhkPath '" /restart "' A_ScriptFullPath '"'
  }
  ExitApp
}
kofifus
  • 17,260
  • 17
  • 99
  • 173