ShellExecute执行外部程序时,判断执行成功与否有以下几种方法:
方法1:使用WshShell.Run(推荐)
Set WshShell = CreateObject("WScript.Shell")
' Run方法返回进程退出码
returnCode = WshShell.Run("notepad.exe", 1, True)
If returnCode = 0 Then
WScript.Echo "程序执行成功"
Else
WScript.Echo "程序执行失败,退出码: " & returnCode
End If
参数说明:
- 第二个参数:窗口样式(1=正常,0=隐藏)
- 第三个参数:True=等待程序结束,False=立即继续
方法2:使用WMI监控进程
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "notepad.exe", 1, False
' 使用WMI检查进程是否存在
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name='notepad.exe'")
If colProcesses.Count > 0 Then
WScript.Echo "程序已启动"
Else
WScript.Echo "程序启动失败"
End If
方法3:使用Shell.Application的ShellExecute(获取错误信息)
Set objShell = CreateObject("Shell.Application")
On Error Resume Next
objShell.ShellExecute "notepad.exe", "", "", "open", 1
If Err.Number <> 0 Then
WScript.Echo "执行失败,错误号: " & Err.Number & ",描述: " & Err.Description
Else
WScript.Echo "执行成功(ShellExecute不提供详细返回状态)"
End If
On Error Goto 0
方法4:结合批处理获取退出码(针对命令行程序)
' 创建批处理文件
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile("run_program.bat")
file.WriteLine("@echo off")
file.WriteLine("notepad.exe")
file.WriteLine("echo 退出码: %errorlevel%")
file.WriteLine("exit %errorlevel%")
file.Close
' 执行并获取退出码
Set WshShell = CreateObject("WScript.Shell")
returnCode = WshShell.Run("run_program.bat", 0, True)
If returnCode = 0 Then
WScript.Echo "成功"
Else
WScript.Echo "失败,退出码: " & returnCode
End If
' 清理临时文件
fso.DeleteFile("run_program.bat")
方法5:使用Exec方法(可获取标准输出)
Set WshShell = CreateObject("WScript.Shell")
Set objExec = WshShell.Exec("cmd /c ping 127.0.0.1")
Do While objExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo "退出码: " & objExec.ExitCode
WScript.Echo "标准输出: " & objExec.StdOut.ReadAll
If objExec.ExitCode = 0 Then
WScript.Echo "执行成功"
End If
推荐方案组合
Function RunProgramAndCheck(programPath, arguments, waitForCompletion)
Dim WshShell, returnCode
Set WshShell = CreateObject("WScript.Shell")
If waitForCompletion Then
' 需要等待程序结束
returnCode = WshShell.Run(Chr(34) & programPath & Chr(34) & " " & arguments, 1, True)
If returnCode = 0 Then
RunProgramAndCheck = True
Else
RunProgramAndCheck = False
WScript.Echo "程序返回错误码: " & returnCode
End If
Else
' 不需要等待,使用错误处理
On Error Resume Next
WshShell.Run Chr(34) & programPath & Chr(34) & " " & arguments, 1, False
If Err.Number = 0 Then
RunProgramAndCheck = True
Else
RunProgramAndCheck = False
WScript.Echo "启动失败: " & Err.Description
End If
On Error Goto 0
End If
End Function
' 使用示例
If RunProgramAndCheck("C:\Program Files\App\app.exe", "/silent", True) Then
WScript.Echo "执行成功"
Else
WScript.Echo "执行失败"
End If
注意事项
ShellExecute vs Run:
ShellExecute更适合打开文档/URL,
Run更适合执行程序并获取状态
程序类型: GUI程序通常返回0表示成功,命令行程序有明确的退出码
权限问题: 某些程序需要管理员权限才能正常运行
路径空格: 包含空格的路径需要用引号包裹
选择哪种方法取决于你的具体需求:是否需要等待程序结束、是否需要获取输出、程序是GUI还是命令行工具等。