<style type="text/css"> .style3 {color: #000; background: rgba(255, 255, 0, 0.4);} </style> </head> <body> <h1>Run / RunWait</h1> <p>Runs an external program. Unlike Run, RunWait will wait until the program finishes before continuing.</p> <pre class="Syntax"> <span class="func">Run</span>, Target <span class="optional">, WorkingDir, Options, OutputVarPID</span> <span class="func">RunWait</span>, Target <span class="optional">, WorkingDir, Options, OutputVarPID</span> </pre> <h2 id="Parameters">Parameters</h2> <dl> <dt>Target</dt> <dd><p>A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or <a href="#verbs">system verb</a> to launch (see remarks). If <em>Target</em> is a local file and no path was specified with it, <a href="../Variables.htm#WorkingDir">A_WorkingDir</a> 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.</p> <p>To pass parameters, add them immediately after the program or document name. For example, <code>Run, MyProgram.exe Param1 Param2</code>.</p> <p>If the program/document name or a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). For example, <code>Run, "My Program.exe" "param with spaces"</code>.</p></dd> <dt>WorkingDir</dt> <dd><p>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 href="../Variables.htm#WorkingDir">A_WorkingDir</a>) will be used.</p></dd> <dt>Options</dt> <dd><p>If omitted, the command launches <em>Target</em> normally and shows a warning dialog whenever <em>Target</em> could not be launched. To change this behavior, specify one or more of the following words:</p> <p><strong>Max</strong>: launch maximized</p> <p><strong>Min</strong>: launch minimized</p> <p><strong>Hide</strong>: launch hidden (cannot be used in combination with either of the above)</p> <p class="note"><strong>Note</strong>: Some applications (e.g. Calc.exe) do not obey the requested startup state and thus Max/Min/Hide will have no effect.</p> <p id="UseErrorLevel"><strong>UseErrorLevel</strong>: UseErrorLevel can be specified alone or in addition to one of the above words (by separating it from the other word with a space). If the launch fails, this option skips the warning dialog, sets <a href="../misc/ErrorLevel.htm">ErrorLevel</a> to the word ERROR, and allows the <a href="../misc/Threads.htm">current thread</a> to continue. If the launch succeeds, RunWait sets <a href="../misc/ErrorLevel.htm">ErrorLevel</a> to the program's exit code, and Run sets it to 0.</p> <p id="LastError">When UseErrorLevel is specified, the variable <strong>A_LastError</strong> is set to the result of the operating system's GetLastError() function. A_LastError is a number between 0 and 4294967295 (always formatted as decimal, not hexadecimal). Zero (0) means success, but any other number means the launch failed. Each number corresponds to a specific error condition (to get a list, search <a href="https://www.microsoft.com">www.microsoft.com</a> for "system error codes"). Like <a href="../misc/ErrorLevel.htm">ErrorLevel</a>, A_LastError is a per-thread setting; that is, interruptions by other <a href="../misc/Threads.htm">threads</a> cannot change it. However, A_LastError is also set by <a href="DllCall.htm#LastError">DllCall()</a>.</p></dd> <dt>OutputVarPID</dt> <dd><p>The name of the variable in which to store the newly launched program's unique <a href="Process.htm">Process ID (PID)</a>. 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 <em>OutputVarPID</em> must be checked in <a href="../misc/Threads.htm">another thread</a> (otherwise, the PID will be invalid because the process will have terminated by the time the line following RunWait executes).</p> <p>After the Run command 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 <code><a href="WinWait.htm">WinWait</a> ahk_pid %OutputVarPID%</code>.</p></dd> </dl> <h2 id="Error_Handling">Error Handling</h2> <p><span class="ver">[v1.1.04+]</span>: This command is able to throw an exception on failure. For more information, see <a href="Catch.htm#RuntimeErrors">Runtime Errors</a>.</p> <p>Run: Does not set <a href="../misc/ErrorLevel.htm">ErrorLevel</a> unless UseErrorLevel (above) is in effect, in which case ErrorLevel is set to the word ERROR upon failure or 0 upon success.</p> <p>RunWait: Sets ErrorLevel to the program's exit code (a signed 32-bit integer). If UseErrorLevel is in effect and the launch failed, the word ERROR is stored.</p> <h2 id="Remarks">Remarks</h2> <p>Unlike Run, RunWait will wait until <em>Target</em> is closed or exits, at which time <a href="../misc/ErrorLevel.htm">ErrorLevel</a> will be set to 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.</p> <p>If <em>Target</em> contains any commas, they must be <a href="../misc/EscapeChar.htm">escaped</a> as highlighted three times in the following example:</p> <pre>Run rundll32.exe shell32.dll<span class="style3">`,</span>Control_RunDLL desk.cpl<span class="style3">`,`,</span> 3 <em>; Opens Control Panel &gt; Display Properties &gt; Settings</em></pre> <p>When running a program via <a href="../Variables.htm#ComSpec">ComSpec</a> (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 quotes. In the following example, the outer quotes are highlighted in yellow:</p> <pre>Run %ComSpec% /c <span class="style3">"</span>"C:\My Utility.exe" "param 1" "second param" &gt;"C:\My File.txt"<span class="style3">"</span></pre> <p>If <em>Target</em> cannot be launched, an error window is displayed and the current thread is exited, unless the string <strong>UseErrorLevel</strong> is included in the third parameter or the error is caught by a <a href="Try.htm">Try</a>/<a href="Catch.htm">Catch</a> statement.</p> <p>Performance may be slightly improved if <em>Target</em> is an exact path, e.g. <code>Run, C:\Windows\Notepad.exe "C:\My Documents\Test.txt"</code> rather than <code>Run, C:\My Documents\Test.txt</code>.</p> <p>Special <a href="../misc/CLSID-List.htm">CLSID folders</a> may be opened via Run. For example:</p> <pre>Run ::{20d04fe0-3aea-1069-a2d8-08002b30309d} <em>; Opens the "My Computer" folder.</em> Run ::{645ff040-5081-101b-9f08-00aa002f954e} <em>; Opens the Recycle Bin.</em></pre> <p id="verbs">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:</p> <table class="info"> <tr> <th style="width:8%">Verb</th> <th abbr="Descr">Description</th> </tr> <tr> <td>*<i>verb</i></td> <td><span class="ver">[AHK_L 57+]:</span> Any system-defined or custom verb. For example: <code>Run *Compile %A_ScriptFullPath%</code>. On Windows Vista and later, the <a href="#RunAs">*RunAs</a> verb may be used in place of the <i>Run as administrator</i> right-click menu item.</td> </tr> <tr> <td>properties</td> <td> <p>Displays the Explorer's properties window for the indicated file. For example: <code>Run, properties "C:\My File.txt"</code></p> <p class="note"><strong>Note</strong>: The properties window will automatically close when the script terminates. To prevent this, use <a href="WinWait.htm">WinWait</a> to wait for the window to appear, then use <a href="WinWaitClose.htm">WinWaitClose</a> to wait for the user to close it.</p> </td> </tr> <tr> <td>find</td> <td>Opens an instance of the Explorer's Search Companion or Find File window at the indicated folder. For example: <code>Run, find D:\</code></td> </tr> <tr> <td>explore</td> <td>Opens an instance of Explorer at the indicated folder. For example: <code>Run, explore %A_ProgramFiles%</code>.</td> </tr> <tr> <td>edit</td> <td>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: <code>Run, edit "C:\My File.txt"</code></td> </tr> <tr> <td>open</td> <td>Opens the indicated file (normally not needed because it is the default action for most file types). For example: <code>Run, open "My File.txt"</code>.</td> </tr> <tr> <td>print</td> <td>Prints the indicated file with the associated application, if any. For example: <code>Run, print "My File.txt"</code></td> </tr> </table> <p>While RunWait is in a waiting state, new <a href="../misc/Threads.htm">threads</a> can be launched via <a href="../Hotkeys.htm">hotkey</a>, <a href="Menu.htm">custom menu item</a>, or <a href="SetTimer.htm">timer</a>.</p> <h2 id="RunAs">Run as Administrator <span class="ver">[AHK_L 57+]</span></h2> <p>For an executable file, the <em>*RunAs</em> verb is equivalent to selecting <em>Run as administrator</em> from the right-click menu of the file. For example, the following code attempts to restart the current script as admin:</p> <pre>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%</pre> <p>If the user cancels the UAC dialog or Run fails for some other reason, the script will simply exit.</p> <p>Using <a href="../Scripts.htm#SlashR">/restart</a> ensures that a <a href="_SingleInstance.htm">single instance</a> prompt is not shown if the new instance of the script starts before ExitApp is called.</p> <p>If UAC is disabled, <em>*RunAs</em> will launch the process without elevating it. Checking for <code>/restart</code> in the command line ensures that the script does not enter a runaway loop in that case. Note that <code>/restart</code> is a built-in switch, so is not included in the <a href="../Scripts.htm#cmd_args">array of command-line parameters</a>.</p> <p>The example can be modified to fit the script's needs:</p> <ul> <li>If the script absolutely requires admin rights, check A_IsAdmin a second time in case <em>*RunAs</em> failed to elevate the script (i.e. because UAC is disabled).</li> <li>To keep the script running even if the user cancels the UAC prompt, move ExitApp into the try block.</li> <li>To keep the script running even if it failed to restart (i.e. because the script file has been changed or deleted), remove ExitApp and use RunWait instead of Run. On success, <code>/restart</code> causes the new instance to terminate the old one. On failure, the new instance exits and RunWait returns.</li> </ul> <p><span class="ver">[v1.0.92.01+]:</span> If UAC is enabled, the AutoHotkey installer registers the <em>RunAs</em> verb for <em>.ahk</em> files, which allows <code>Run *RunAs script.ahk</code> to launch a script as admin with the default executable.</p> <h2 id="Related">Related</h2> <p><a href="RunAs.htm">RunAs</a>, <a href="Process.htm">Process</a>, <a href="Exit.htm">Exit</a>, <a href="../misc/CLSID-List.htm">CLSID List</a>, <a href="DllCall.htm">DllCall()</a></p> <h2 id="Examples">Examples</h2> <div class="ex" id="ExBasic"> <p><a class="ex_number" href="#ExBasic"></a> Run is able to launch Windows system programs from any directory. Note that executable file extensions such as .exe can be omitted.</p> <pre>Run, notepad</pre> </div> <div class="ex" id="ExURL"> <p><a class="ex_number" href="#ExURL"></a> Run is able to launch URLs:</p> <p>The following opens an internet address in the user's default web browser.</p> <pre>Run, https://www.google.com</pre> <p>The following opens the default e-mail application with the recipient filled in.</p> <pre>Run, mailto:someone@somedomain.com</pre> <p>The following does the same as above, plus the subject and body.</p> <pre>Run, mailto:someone@somedomain.com?subject=This is the subject line&amp;body=This is the message body's text.</pre> </div> <div class="ex" id="ExErrorLevel"> <p><a class="ex_number" href="#ExErrorLevel"></a> Opens a document in a maximized application and displays a custom error message on failure.</p> <pre>Run, ReadMe.doc, , Max UseErrorLevel if (ErrorLevel = "ERROR") MsgBox The document could not be launched.</pre> </div> <div class="ex" id="ExVerb"> <p><a class="ex_number" href="#ExVerb"></a> Runs the dir command in minimized state and stores the output in a text file. After that, the text file and its properties dialog will be opened.</p> <pre>#Persistent RunWait, %ComSpec% /c dir C:\ &gt;&gt;C:\DirTest.txt, , Min Run, C:\DirTest.txt Run, properties C:\DirTest.txt</pre> </div> <div class="ex" id="ExCLSID"> <p><a class="ex_number" href="#ExCLSID"></a> Run is able to launch <a href="../misc/CLSID-List.htm">CLSIDs</a>:</p> <p>The following opens the recycle bin.</p> <pre>Run, ::{645ff040-5081-101b-9f08-00aa002f954e}</pre> <p>The following opens the "My Computer" directory.</p> <pre>Run, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}</pre> </div> <div class="ex" id="ExMultipleCmds"> <p><a class="ex_number" href="#ExMultipleCmds"></a> To run multiple commands consecutively, use "&amp;&amp;" between each.</p> <pre>Run, %ComSpec% /c dir /b &gt; C:\list.txt &amp;&amp; type C:\list.txt &amp;&amp; pause</pre> </div> <div class="ex" id="StdOut"> <p><a class="ex_number" href="#StdOut"></a> The following functions can be used to run a command and retrieve its output or to run multiple commands in one go and retrieve their output.</p> <pre>MsgBox % RunWaitOne("dir " A_ScriptDir) MsgBox % RunWaitMany(" ( echo Put your commands here, echo each one will be run, echo and you'll get the output. )") RunWaitOne(command) { <em>; WshShell object: <a href="http://msdn.microsoft.com/en-us/library/aew9yb99">http://msdn.microsoft.com/en-us/library/aew9yb99</a></em> shell := ComObjCreate("WScript.Shell") <em>; Execute a single command via cmd.exe</em> exec := shell.Exec(ComSpec " /C " command) <em>; Read and return the command's output</em> return exec.StdOut.ReadAll() } RunWaitMany(commands) { shell := ComObjCreate("WScript.Shell") <em>; Open cmd.exe with echoing of commands disabled</em> exec := shell.Exec(ComSpec " /Q /K echo off") <em>; Send the commands to execute, separated by newline</em> exec.StdIn.WriteLine(commands "`nexit") <em>; Always exit at the end!</em> <em>; Read and return the output of all commands</em> return exec.StdOut.ReadAll() } </pre> </div> <div class="ex" id="ExecScript"> <p><a class="ex_number" href="#ExecScript"></a> Executes the given code as a new AutoHotkey process.</p> <pre>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() } <em>; Example:</em> InputBox expr,, Enter an expression to evaluate as a new script.,,,,,,,, Asc("*") result := ExecScript("FileAppend % (" expr "), *") MsgBox % "Result: " result </pre> </div> </body> </html>