Run / RunWait

外部プログラムを実行します。Runとは異なり、RunWaitはプログラムが終了するまで待機してから続行します。

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

パラメータ

Target

型:文字列

A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), CLSID, or system verb to launch (see remarks). If Target is a local file and no path was specified with it, how the file is located typically depends on the type of file and other conditions. See Interpretation of Target for details.

To pass parameters, add them immediately after the program or document name as follows:

Run 'MyProgram.exe Param1 Param2'

If the program/document name or a parameter contains spaces, it is safest to enclose it in double quotes as follows (even though it may work without them in some cases):

Run '"My Program.exe" "param with spaces"'
WorkingDir

型:文字列

If blank or omitted, the script's own working directory (A_WorkingDir) will be used. Otherwise, specify the initial working directory to be used by the new process. This typically also affects relative paths in Target, but interpretation of command-line parameters depends on the target program.

Options

型:文字列

If blank or omitted, Target will be launched normally. Otherwise, specify one or more of the following options:

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

型:VarRef

省略したときは、対応する値は保存されません。Otherwise, specify a reference to the output variable in which to store the newly launched program's unique Process ID (PID). PIDを決定できなかった場合、この変数は空白になります。これは通常、直接の実行ファイルではなく、システムの動詞、文書、ショートカットが起動された場合に起こります。RunWaitもこのパラメータをサポートしていますが、そのOutputVarPID別のスレッドでチェックする必要があります(そうしないと、RunWaitに続く行が実行されるまでにプロセスが終了してしまうため、PIDは無効となります)。

Run関数がPIDを取得した後、プロセスによって作成されるウィンドウは、まだ存在しないかもしれません。少なくとも1つのウィンドウが作成されるのを待つには、WinWait"ahk_pid " OutputVarPIDを使用します。

戻り値

型:整数

RunWaitはRunと異なり、Targetがクローズされるか終了するまで待機し、その時の戻り値はプログラムの終了コード(符号付き32ビット整数)となります。プログラムによっては、まだ実行中であるにもかかわらず、すぐに戻ってくるように見えるものがありますが、これは別のプロセスを生成するものです。

エラー処理

Targetを起動できない場合、Try/Catch文によってエラーが捕捉されない限り、例外が発生し(つまり、エラーウィンドウが表示され)、現在のスレッドが終了する。事例:

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

組込変数A_LastErrorには、オペレーティングシステムのGetLastError()関数の結果が設定されます。

Interpretation of Target

Run/RunWait itself does not interpret command-line parameters or search for the target file. Instead, it attempts to execute the target as follows:

If Target specifies a name but not a directory, 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. The exact search order depends on whether CreateProcess and/or ShellExecuteEx is called. If CreateProcess is called, the application directory (which contains the AutoHotkey interpreter or compiled script) takes precedence over the working directory specified by WorkingDir. To avoid this, specify the directory; e.g. .\program.exe.

When ShellExecuteEx is being attempted, Target is interpreted as follows:

備考

ComSpec(cmd.exe)を使ってプログラムを実行する場合(プログラムの入力や出力をリダイレクトする必要があるため)、実行ファイルのパスや名前にスペースが含まれている場合は、その文字列全体を外側の引用符で囲む必要があります。以下の例では、外側の引用符が黄色で強調表示されています:

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

Run"C:゙My DocumentsTest.txt "よりもRun 'C:゙WindowsNotepad.exe "C:゙My DocumentsTest.txt"のようにTargetが完全パスであればパフォーマンスは若干向上するかもしれません。

Special CLSIDs may be opened via Run. Most of them can be opened by using the shell:prefix. Some can be opened without it. 事例:

Run "shell:::{D20EA4E1-3957-11D2-A40B-0C5020524153}"  ; Windows Tools.
Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"  ; This PC (formerly My Computer or Computer).
Run "::{645FF040-5081-101B-9F08-00AA002F954E}"  ; Recycle Bin.

システム動詞は、エクスプローラーのファイルの右クリックメニューで利用できるアクションに対応しています。動詞を指定せずにファイルを起動した場合、そのファイルタイプのデフォルトの動詞(通常は「open」)が使用されます。指定された場合、動詞の後にターゲットファイル名が続くようにする。現在、以下の動詞に対応しています:

Verb 説明
*verb システムで定義された、またはカスタムされた任意の動詞。事例:Run "*Compile " A_ScriptFullPath. 管理者として実行右クリックメニューの代わりに*RunAs動詞を使用することができます。
properties

表示されているファイルのエクスプローラーのプロパティウィンドウを表示します。事例:Run 'properties "C:\My File.txt"'

Note: The properties window will automatically close when the script terminates. これを防ぐには、WinWaitでウィンドウが表示されるのを待ち、WinWaitCloseでユーザーがウィンドウを閉じるのを待ちます。

find エクスプローラの「検索仲間」または「ファイル検索」ウィンドウのインスタンスを、指定されたフォルダーで開くことができます。事例:Run "find D:\"
explore 指定されたフォルダーにエクスプローラーのインスタンスを開きます。事例:Run "explore " A_ProgramFiles.
edit 指示されたファイルを編集用に開きます。表示されたファイルの種類に「編集」アクションが関連付けられていない場合は、動作しないことがあります。事例:Run 'edit "C:\My File.txt"'
open 指定されたファイルを開く(ほとんどのファイルタイプでデフォルトの動作であるため、通常は必要ありません)。事例:Run 'open "My File.txt"'.
print 指定されたファイルを、もしあれば、関連するアプリケーションとともに印刷します。事例:Run 'print "My File.txt"'

RunWaitが待機状態にある間、ホットキーカスタムメニュー項目、またはタイマーを使って新しいスレッドを起動することができます。

Run as Administrator

実行ファイルの場合、*RunAs動詞は、そのファイルの右クリックメニューから「管理者として実行」を選択することと同じです。例えば、次のコードは、現在のスクリプトを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 User Account Control (UAC) dialog or Run fails for some other reason, the script will simply exit.

/restartを使用すると、ExitAppが呼び出される前にスクリプトの新しいインスタンスが開始されても、単一インスタンスのプロンプトが表示されないようにします。

UACが無効の場合、*RunAsは昇格させずにプロセスを起動します。コマンドラインで/restartをチェックすることで、その場合にスクリプトが暴走ループに入らないようにします。なお、/restartは組み込みのスイッチなので、コマンドラインパラメータの配列には含まれません。

この例は、スクリプトの必要性に応じて変更することができます:

AutoHotkeyのインストーラは、.ahkファイルに対してRunAs動詞を登録しており、Run "*RunAs script.ahk"でスクリプトを管理者として起動できます。

RunAs, Process functions, Exit, CLSID List, DllCall

Runは、任意のディレクトリからWindowsシステムのプログラムを起動することができます。なお、.exeなどの実行ファイルの拡張子は省略可能です。

Run "notepad"

Runは、URLの起動が可能です:

以下は、ユーザーのデフォルトのウェブブラウザでインターネットアドレスを開くものです。

Run "https://www.google.com"

以下は、受信者が記入されたデフォルトの電子メールアプリケーションを開くものです。

Run "mailto:someone@somedomain.com"

以下は、上記と同じに、件名と本文を追加します。

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

最大化されたアプリケーションでドキュメントを開き、失敗時にカスタムエラーメッセージを表示します。

try Run("ReadMe.doc", , "Max")
if A_LastError
    MsgBox "The document could not be launched."

最小化状態でdirコマンドを実行し、出力をテキストファイルに保存します。その後、テキストファイルとそのプロパティダイアログが開かれます。

RunWait A_ComSpec " /c dir C:\ >>C:\DirTest.txt", , "Min"
Run "C:\DirTest.txt"
Run "properties C:\DirTest.txt"
Persistent  ; Keep the script from exiting, otherwise the properties dialog will close.

RunはCLSIDを起動することができます:

The following opens the Recycle Bin.

Run "::{645FF040-5081-101B-9F08-00AA002F954E}"

The following opens This PC (formerly My Computer or Computer).

Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"

複数のコマンドを連続して実行する場合は、各コマンドの間に"&&"を使用します。

Run A_ComSpec "/c dir /b > C:\list.txt && type C:\list.txt && pause"

以下のカスタム関数を使用して、コマンドを実行してその出力を取得したり、複数のコマンドを一度に実行してその出力を取得したりすることができます。WshShellオブジェクトについては、Microsoft Docsを参照してください。

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) {
    shell := ComObject("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 := ComObject("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()
}

与えられたコードを新しいAutoHotkeyのプロセスとして実行します。

ExecScript(Script, Wait:=true)
{
    shell := ComObject("WScript.Shell")
    exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *")
    exec.StdIn.Write(Script)
    exec.StdIn.Close()
    if Wait
        return exec.StdOut.ReadAll()
}

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