Run[Wait]

Runs an external program. Unlike Run, RunWait will wait until the program finishes before continuing.

Run Target , WorkingDir, Options, OutputVarPID
ExitCode := RunWait(Target , WorkingDir, Options, OutputVarPID)

Parameters

Target

Type: String

A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or system verb to launch (see remarks). If Target is a local file and no path was specified with it, A_WorkingDir will be searched first. If no matching file is found there, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders.

To pass parameters, add them immediately after the program or document name. If a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases).

WorkingDir

Type: String

The working directory for the launched item. Do not enclose the name in double quotes even if it contains spaces. If omitted, the script's own working directory (A_WorkingDir) will be used.

Options

Type: String

If omitted, the function launches Target normally. To change this behavior, specify one or more of the following words:

Max: launch maximized

Min: launch minimized

Hide: launch hidden (cannot be used in combination with either of the above)

Note: Some applications (e.g. Calc.exe) do not obey the requested startup state and thus Max/Min/Hide will have no effect.

OutputVarPID

Type: Variable

The name of the variable in which to store the newly launched program's unique Process ID (PID). The variable will be made blank if the PID could not be determined, which usually happens if a system verb, document, or shortcut is launched rather than a direct executable file. RunWait also supports this parameter, though its OutputVarPID must be checked in another thread (otherwise, the PID will be invalid because the process will have terminated by the time the line following RunWait executes).

After the Run function retrieves a PID, any windows to be created by the process might not exist yet. To wait for at least one window to be created, use WinWait "ahk_pid " OutputVarPID.

Return Value

Type: Integer

Unlike Run, RunWait will wait until Target is closed or exits, at which time the return value will be the program's exit code (as a signed 32-bit integer). Some programs will appear to return immediately even though they are still running; these programs spawn another process.

Error Handling

If Target cannot be launched, an exception is thrown (that is, an error window is displayed) and the current thread is exited, unless the error is caught by a Try/Catch statement. For example:

try
    Run "NonExistingFile"
catch
    MsgBox "File does not exist."

The built-in variable A_LastError is set to the result of the operating system's GetLastError() function.

Remarks

When running a program via Comspec (cmd.exe) -- perhaps because you need to redirect the program's input or output -- if the path or name of the executable contains spaces, the entire string should be enclosed in an outer pair of single-quote marks. In the following example, the outer single-quote marks are shown in red and all the inner double-quote marks are shown in black:

Run A_ComSpec ' /c "C:\My Utility.exe" "param 1" "second param" >"C:\My File.txt"'

Performance may be slightly improved if Target is an exact path, e.g. Run 'C:\Windows\Notepad.exe "C:\My Documents\Test.txt"' rather than Run "C:\My Documents\Test.txt".

Special CLSID folders may be opened via Run. For example:

Run "::{20d04fe0-3aea-1069-a2d8-08002b30309d}"  ; Opens the "My Computer" folder.
Run "::{645ff040-5081-101b-9f08-00aa002f954e}"  ; Opens the Recycle Bin.

System verbs correspond to actions available in a file's right-click menu in the Explorer. If a file is launched without a verb, the default verb (usually "open") for that particular file type will be used. If specified, the verb should be followed by the name of the target file. The following verbs are currently supported:

*verb Any system-defined or custom verb. For example: Run "*Compile " A_ScriptFullPath
On Windows Vista and later, the *RunAs verb may be used in place of the Run as administrator right-click menu item.
properties

Displays the Explorer's properties window for the indicated file. For example: Run 'properties "C:\My File.txt"'

Note: The properties window will automatically close when the script terminates. To prevent this, use WinWait to wait for the window to appear, then use WinWaitClose to wait for the user to close it.

find Opens an instance of the Explorer's Search Companion or Find File window at the indicated folder. For example: Run "find D:\"
explore Opens an instance of Explorer at the indicated folder. For example: Run "explore " A_ProgramFiles.
edit Opens the indicated file for editing. It might not work if the indicated file's type does not have an "edit" action associated with it. For example: Run 'edit "C:\My File.txt"'
open Opens the indicated file (normally not needed because it is the default action for most file types). For example: Run 'open "My File.txt"'.
print Prints the indicated file with the associated application, if any. For example: Run 'print "My File.txt"'

While RunWait is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.

Run as Administrator

For an executable file, the *RunAs verb is equivalent to selecting Run as administrator from the right-click menu of the file. For example, the following code attempts to restart the current script as admin:

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
}

MsgBox "A_IsAdmin: " A_IsAdmin "`nCommand line: " full_command_line

If the user cancels the UAC dialog or Run fails for some other reason, the script will simply exit.

Using /restart ensures that a single instance prompt is not shown if the new instance of the script starts before ExitApp is called.

If UAC is disabled, *RunAs will launch the process without elevating it. Checking for /restart in the command line ensures that the script does not enter a runaway loop in that case. Note that /restart is a built-in switch, so is not included in the array of command-line parameters.

The example can be modified to fit the script's needs:

If UAC is enabled, the AutoHotkey installer registers the RunAs verb for .ahk files, which allows Run "*RunAs script.ahk" to launch a script as admin with the default executable.

Related

RunAs, Process functions, Exit, CLSID List, DllCall

Examples

Run "Notepad.exe", "C:\My Documents", "max"

Run "mailto:someone@domain.com?subject=This is the subject line&body=This is the message body's text."

try Run("ReadMe.doc", , "Max")  ; Launch maximized and don't display dialog if it fails.
if A_LastError
    MsgBox "The document could not be launched."

RunWait A_ComSpec " /c dir c:\ >>c:\DirTest.txt", , "min"
Run "c:\DirTest.txt"
Run "properties c:\DirTest.txt"

Run "http://www.google.com" ; i.e. any URL can be launched.
Run "mailto:someone@somedomain.com"  ; This should open the default e-mail application.

Run "::{20d04fe0-3aea-1069-a2d8-08002b30309d}"  ; Opens the "My Computer" folder.
Run "::{645ff040-5081-101b-9f08-00aa002f954e}"  ; Opens the Recycle Bin.

; To run multiple commands consecutively, use "&&" between each:
Run A_ComSpec " /c dir /b > C:\list.txt && type C:\list.txt && pause"

; Following line opens Control Panel > Display Properties > Settings:
Run "rundll32.exe shell32.dll,Control_RunDLL desk.cpl,, 3"
; The following can be used to run a command and retrieve its output:
MsgBox RunWaitOne("dir " A_ScriptDir)

; ...or run multiple commands in one go and retrieve their output:
MsgBox RunWaitMany("
(
echo Put your commands here,
echo each one will be run,
echo and you'll get the output.
)")

RunWaitOne(command) {
    ; WshShell object: http://msdn.microsoft.com/en-us/library/aew9yb99
    shell := ComObjCreate("WScript.Shell")
    ; Execute a single command via cmd.exe
    exec := shell.Exec(A_ComSpec " /C " command)
    ; Read and return the command's output
    return exec.StdOut.ReadAll()
}

RunWaitMany(commands) {
    shell := ComObjCreate("WScript.Shell")
    ; Open cmd.exe with echoing of commands disabled
    exec := shell.Exec(A_ComSpec " /Q /K echo off")
    ; Send the commands to execute, separated by newline
    exec.StdIn.WriteLine(commands "`nexit")  ; Always exit at the end!
    ; Read and return the output of all commands
    return exec.StdOut.ReadAll()
}
; ExecScript: Executes the given code as a new AutoHotkey process.
ExecScript(Script, Wait:=true)
{
    shell := ComObjCreate("WScript.Shell")
    exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *")
    exec.StdIn.Write(script)
    exec.StdIn.Close()
    if Wait
        return exec.StdOut.ReadAll()
}

; Example:
expr := InputBox("Enter an expression to evaluate as a new script.",,, 'Ord("*")')
result := ExecScript('FileAppend ' expr ', "*"')
MsgBox "Result: " result