从批处理文件返回错误消息 [英] Return error message from batch file

查看:66
本文介绍了从批处理文件返回错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从VBA脱壳到批处理文件,以启动exec文件,例如Notepad.exe.如果找不到exec文件,我想将指示或消息返回给VBA.到目前为止,我一直在通过让蝙蝠将消息写到文本文件中,然后让VBA检查该文件来做到这一点.这种方法似乎有点笨拙,但到目前为止,我还没有遇到另一种方法.

I'm shelling to a batch file from VBA, to launch an exec file, such as Notepad.exe. I would like to return an indication or message back to VBA if the exec file wasn't found. So far, I've been doing this by having the bat write a message to a text file, then have VBA examine this file. This approach seems a bit kludgy, but so far I haven't come across an alternate method.

@echo off

set EM="C:\Msg.txt"
if exist %EM% del %EM%

set FL=%SystemRoot%\system32\xnotepad.exe

if not exist %FL% (
echo %FL% not found > %EM%
goto done
)

Start "" %FL%

:done

推荐答案

在VBA中,

Dim oSHELL, batchname, usr, pass, exitcode
Set oSHELL = VBA.CreateObject("WScript.Shell")
usr="username"
pass="password"
batchname="batchFile.bat"

' Arguments ToRun, Style (0=hide), Waitforend
exitcode = oSHELL.Run(""""+batchname+""" """+usr+""" """+pass+"""", 0, True)

并在您的批次中

exit somenumber

应将 somenumber 返回到 exitcode

我使用的实际代码:

Sub q27097252()
Dim oSHELL, batchname, usr, pass, exitcode
Set oSHELL = VBA.CreateObject("WScript.Shell")
usr = ""
pass = ""
batchname = "c:\106x\q27097252.bat"

' Arguments ToRun, Style (0=hide), Waitforend
exitcode = oSHELL.Run("""" + batchname + """ """ + usr + """ """ + pass + """", 0, True)
MsgBox (exitcode)
End Sub

使用批处理 c:\ 106x \ q27097252.bat

@ECHO OFF
SETLOCAL
EXIT %time:~-1%

GOTO :EOF

在VBA代码编辑器/F5中对我来说非常好(预期结果:消息框随机显示0..9)

Ran perfectly well for me in VBA code editor/F5 (expected result: messagebox showing 0..9 at random)

在使用Windows XP时,遵循以下注释/解决方案:

Following comment/solution when using Windows XP:

看来, exit/b number 选项只是设置了 errorlevel ,而 exit number 实际上是设置了终止代码.
在XP下,终止代码为0,因为 cmd.exe 实际上已正常终止-而Windows 7(及更高版本)似乎将当前 errorlevel 分配为 cmd的退出代码.exe 进程.
因此,请优先使用退出编号以与XP兼容-代码已调整为适合.

It would appear the exit /b number option simply sets errorlevel whereas exit number actually sets the termination code.
Termination code is 0 under XP since cmd.exe actually terminated normally — whereas Windows 7 (and later) appears to assign the current errorlevel as exit code for the cmd.exe process.
Hence, use exit number by preference for compatibility with XP — code adjusted to suit.

这篇关于从批处理文件返回错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆