通过VBScript执行批处理文件后读取文本文件

时间:2013-11-13 03:29:28

标签: batch-file vbscript

我必须使用run执行批处理文件,并在文本文件中获取输出,并在该文件中搜索代码片段的字符串,如下所示,

用于运行bat文件

 Set objShell = WScript.CreateObject("WScript.Shell")
 MsgBox("Compiling Source files..Please wait..")
 objShell.Run CHR(34) & ".\lib\Compile.bat" & CHR(34) & " > compile.txt" & CHR(34), 0 ,True

我发现运行后执行不会进入下一行,但如果我在任务管理器中结束cmd.exe进程,则会执行。

我已经提到了在下面这个读完之后等待过程完成的事实,

Dim objFSO, strLine, objReadFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.OpenTextFile("./compile.txt", 1 , true)
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
    ....
    ....

如何执行compile.bat并且正在创建compile.txt但是不会发生读取过程。如果我从运行命令中删除“true”,则会收到“compile.txt文件不存在”错误。

我不知道哪里出错了,请帮帮我..

2 个答案:

答案 0 :(得分:1)

从你的所有问题我都假设你的问题背后的故事 是这样的:

你的老板D. Vader先生,要求你开发构建系统 他的Java应用程序。 “好的”,你说,“让我们使用Eclipse和/或Ant。” “没有”,维德先生说,“我们将拥有一支现代化的BS,其中包括.BAT和一个 按钮GUI“。

所以你建立了一个实验项目:

tree /a /f .
E:\TRIALS\SOTRIALS\ANSWERS\19944721
|
+---vbs
|   |   javacompile.hta
|   |   javacompile.vbs
|
\---java
    +---good
    |       Good.java
    |
    \---bad
            Bad.java

从最小的Good.java开始:

class Good {
  public static void main(String[] args) {
    System.out.println("use Eclipse!");
  }
}

你确认了:

javac Good.java
- no news are good news --

echo %ERRORLEVEL%
0 <-- javac may set ERRORLEVEL

java Good
use Eclipse! <-- it works

坏的相同程序:

class Bad {
  public static void main(String[] args) {
    System.out.println("D. Vader says: 'Use .bat and one button GUI!'.");
  }

javac Bad.java
Bad.java:4: reached end of file while parsing
  }
   ^     <-- javac finds the missing }
1 error

echo %ERRORLEVEL%
1 <-- javac really sets ERRORLEVEL

然后你编写了最小的GUI:javacompile.hta

<html>
 <head>
  <Title>JavaCompile</Title>
  <hta:application id="javacompile" scroll = "no">
  <script type="text/vbscript" src="javacompile.vbs"></script>
 </head>
 <body>
  <form>
   <input type="button" id="bttCheckBasics" value="Check Basics"/>
  <form>
 </body>
</html>

和'后面的代码'javacompile.vbs

Option Explicit

Dim goFS    : Set goFS = CreateObject("Scripting.FileSystemObject")

' document.location: "file:///E:/trials/SoTrials/answers/19944721/vbs/javacompile.hta"
Dim gsVbsF  : gsVbsF  = Replace(goFS.GetParentFolderName(Mid(document.location, 9)), "/", "\")
Dim gsJavaF : gsJavaF = goFS.GetAbsolutePathName(goFS.BuildPath(gsVbsF, "..\java"))
Dim gsGoodF : gsGoodF = goFS.BuildPath(gsJavaF, "good")
Dim gsBadF  : gsBadF  = goFS.BuildPath(gsJavaF, "bad")

Sub bttCheckBasics_onclick()
  MsgBox "Sub bttCheckBasics_onclick() was called."
  MsgBox Join(Array("Known Folders:", gsVbsF, gsJavaF, gsGoodF, gsBadF), vbCrLf)
End Sub

并验证GUI知道在哪里(并且自动绑定有效)。

(Copy from MessageBox)
Known Folders:
E:\trials\SoTrials\answers\19944721\vbs
E:\trials\SoTrials\answers\19944721\java
E:\trials\SoTrials\answers\19944721\java\good
E:\trials\SoTrials\answers\19944721\java\bad
---------------------------
OK
---------------------------

为了让球滚动,你在.hta

上添加了一个按钮
   <br/>
   <input type="button" id="bttKiss" value="Keep It Simple, Stupid"/>

和vbs的一些代码:

Sub bttKiss_onclick()
  MsgBox "Sub bttKiss_onclick() was called."
  KissCompile gsGoodF, "Good.java", "bgood.bat"
  KissCompile gsBadF, "Bad.java", "bbat.bat"
End Sub

Sub KissCompile( sF, sJava, sBat)
  goWSH.CurrentDirectory = sF
  Dim sCmd  : sCmd      = Join(Array("javac", sJava))
  Dim oExec : Set oExec = goWSH.Exec(sCmd)
  Do Until cnWshFinished = oExec.Status : Loop
  MsgBox Join(Array(qq(sCmd), "(javac) ExitCode:", oExec.ExitCode))
  If 0 <> oExec.ExitCode Then MsgBox oExec.StdErr.ReadAll(), vbAbortRetryIgnore, "You messed it up, Mr. Vader!"
End Sub

Function qq(s)
  qq = """" & s & """"
End Function

现在,GUI显示两个MessageBox,用于坏情况:

---------------------------
"javac Bad.java" (javac) ExitCode: 1
---------------------------
OK
---------------------------

---------------------------
You messed it up, Mr. Vader!
---------------------------
Bad.java:4: reached end of file while parsing
  }
   ^
1 error
---------------------------

先生。维达并不觉得好笑:整个地方都是黑色的窗户而不是单一的.BAT! 你设置goWSH.CurrentDirectory的巧妙技巧并不令人印象深刻 他一点都没有。

所以你写了bgood.bat:

@echo off
javac Good.java
IF ERRORLEVEL 1 GOTO :bingo
echo SUCCESS
GOTO :end
:bingo
echo FAILURE
:end

和相应的bbad.bat。一些测试:

bbad
Bad.java:4: reached end of file while parsing
  }
   ^
1 error
FAILURE
JAVA E:\trials\SoTrials\answers\19944721\java\bad
echo %ERRORLEVEL%
1

现在故事改变为科幻小说。你会按照我的建议去做 使用我的BTicks function略微修改以更好地处理目录并减去删除日志文件的错误。所以util.vbs看起来像

Option Explicit

Const cnWshRunning       =  0 ' The job is still running.
Const cnWshFinished      =  1 ' The job has completed.
Const SW_SHOWMINNOACTIVE =  7
Const ForReading         =  1

Function qq(s)
  qq = """" & s & """"
End Function

' BTicks - execute sCmd via WSH.Run
'  aRet( 0 ) : goWSH.Run() result
'  aRet( 1 ) : StdErr / error message
'  aRet( 2 ) : StdOut
'  aRet( 3 ) : command to run
Function BTicks(sExecF, sLogF, sCmd )
  goWSH.CurrentDirectory = sExecF
  Dim aRet    : aRet     = Array(-1, "", "", "")
  Dim sFSpec1 : sFSpec1  = goFS.BuildPath(sLogF, goFS.GetTempName() )
  Dim sFSpec2 : sFSpec2  = goFS.BuildPath(sLogF, goFS.GetTempName() )

  aRet(3) = Join(Array( _
       qq("%comspec%") _
     , "/c" _
     , qq(Join(Array( _
            sCmd _
          , "1>" & qq(sFSpec1) _
          , "2>" & qq(sFSpec2) _
  )))))
  Dim aErr
 On Error Resume Next
  aRet(0) = goWSH.Run(aRet( 3 ), SW_SHOWMINNOACTIVE, True)
  aErr    = Array(Err.Number, Err.Description, Err.Source)
 On Error GoTo 0
  If 0 <> aErr(0) Then
     aRet(0) = aErr(0)
     aRet(1) = Join(Array(aErr(1), aErr(2), "(BTicks)"), vbCrLf)
     BTicks  = aRet
     Exit Function
  End If

  Dim nIdx : nIdx = 1
  Dim sFSpec
  For Each sFSpec In Array(sFSpec2, sFSpec1)
      If goFS.FileExists(sFSpec) Then
         Dim oFile : Set oFile = goFS.GetFile(sFSpec)
         If 0 < oFile.Size Then
            aRet(nIdx) = oFile.OpenAsTextStream(ForReading).ReadAll()
         End If
         oFile.Delete
      End If
      nIdx = nIdx + 1
  Next
  BTicks = aRet
End Function

由于必须包含此文件,因此不需要“旧”按钮 再过,javacompile.hta改为

<html>
 <head>
  <Title>JavaCompile</Title>
  <hta:application id="javacompile" scroll = "no">
  <script type="text/vbscript" src="javacompile.vbs"></script>
  <script type="text/vbscript" src="util.vbs"></script>
 </head>
 <body>
  <form>
   <input type="button" id="bttBTicks" value="Use BTicks, Stupid"/>
  <form>
 </body>
</html>

和javacompile.vbs也变短了:

Option Explicit

Dim goFS    : Set goFS = CreateObject("Scripting.FileSystemObject")

' document.location: "file:///E:/trials/SoTrials/answers/19944721/vbs/javacompile.hta"
Dim gsVbsF  : gsVbsF  = Replace(goFS.GetParentFolderName(Mid(document.location, 9)), "/", "\")
Dim gsJavaF : gsJavaF = goFS.GetAbsolutePathName(goFS.BuildPath(gsVbsF, "..\java"))
Dim gsGoodF : gsGoodF = goFS.BuildPath(gsJavaF, "good")
Dim gsBadF  : gsBadF  = goFS.BuildPath(gsJavaF, "bad")

Dim goWSH : Set goWSH = CreateObject( "WScript.Shell" )

Sub bttBTicks_onclick()
  MsgBox "Sub bttUseBTicks_onclick() was called."
  Dim aRet
  aRet = BTicksCompile(gsGoodF, "javac Good.java")
  aRet = BTicksCompile(gsGoodF, "bgood.bat")
  aRet = BTicksCompile(gsBadF , "javac Bad.java")
  aRet = BTicksCompile(gsBadF , "bbad.bat")
End Sub

Function BTicksCompile(sF, sCmd)
  BTicksCompile = BTicks(sF, gsVbsF, sCmd)
  MsgBox Join(BTicksCompile, vbCrLf & "--------" & vbCrLf)
End Function

现在没有更多的黑盒子,最后一个显示(对于bbad.bat)显示 神奇的单词FAILURE。

---------------------------
0
--------
Bad.java:4: reached end of file while parsing
  }
   ^
1 error
--------
FAILURE
--------
"%comspec%" /c "bbad.bat 1>"E:\trials\SoTrials\answers\19944721\vbs\rad6CE21.tmp" 2>"E:\trials\SoTrials\answers\19944721\vbs\radC7CE6.tmp""
---------------------------
OK   
---------------------------

答案 1 :(得分:0)

你能指定绝对路径吗?

如果对true使用objFSO.OpenTextFile参数,那么如果找不到该文件,它将创建文件。我不明白为什么在你的情况下你会想要这样做,这可以解释你为什么不“阅读”文件。如果你刚刚在某个地方创建了它,它就会是空的。

如果您知道compile.bat正在创建文本文件,则下一步是找出OpenTextFile找不到它的原因。如果使用绝对路径,则可以快速解决此问题。

如果绝对路径不是一个选项,那么使用MsgBox WScript.ScriptFullName或其他东西验证脚本运行的路径。

您可能也会这样做,这会使用脚本运行位置的相对路径 strPath = Replace(WScript.ScriptFullName,WScript.ScriptName,"")
objShell.Run ".\lib\Compile.bat" & " > " & strPath & "compile.txt", 0 ,True
Set objReadFile = objFSO.OpenTextFile(strPath & "compile.txt",1)