Solved

How do I get VB app to stop when batch exe fails?

Posted on 2004-10-13
8
664 Views
Last Modified: 2011-10-03
I dynamically generate a Batch exe and execute it.  My VB application waits until the batch exe has completed before continuing.

The code below returns an errorlevel of 1, how do I code my VB application to end when the batch exe fails with a errorlevel > 0?


Option Explicit

Dim gRWBackupBatchFileName

Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessID As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const STANDARD_RIGHTS_REQUIRED = &HF0000
Private Const PROCESS_QUERY_INFORMATION As Long = &H400
Private Const STILL_ACTIVE As Long = &H103

Private Sub Form_Load()

     Call CreateRWBackupBatch
     Call ExecuteRWBackupBatch
     MsgBox ("Test failed!")
     End
           
End Sub

Public Sub CreateRWBackupBatch()

    On Error GoTo er_CreateRWBackupBatch
   
    gRWBackupBatchFileName = App.Path & "\test.bat"
    Open gRWBackupBatchFileName For Output Access Write Lock Read Write As 1      
    Print #1, "@echo off"
    Print #1, ""
    Print #1, "copy x.txt y.txt"
    Print #1, ""
    Print #1, "echo %errorlevel%"
    Print #1, "exit"  
    Close #1
   
er_CreateRWBackupBatch:
   
    If Err.Number <> 0 Then
        MsgBox Str(Err.Number) & ": " & Err.Description, , "Create Batch Error"
        End
    End If

End Sub

Public Sub ExecuteRWBackupBatch()
   
    On Error GoTo er_ExecuteRWBackupBatch
   
    WaitForProcess Shell(gRWBackupBatchFileName, vbMinimizedNoFocus)

er_ExecuteRWBackupBatch:

    If Err.Number <> 0 Then
        MsgBox Str(Err.Number) & ": " & Err.Description, , "Execute Batch Error"
        End
    End If
   
End Sub

Public Function WaitForProcess(ProcessID As Long) As Long
   
    Dim hProcess As Long
    Dim RetVal As Long
   
    RetVal = -1 'Default return value
    hProcess = OpenProcess(STANDARD_RIGHTS_REQUIRED + PROCESS_QUERY_INFORMATION, 0, ProcessID)  ' Try to open process
   
    'Start polling to see if the process has terminated
    If hProcess <> 0 Then
        Do
            GetExitCodeProcess hProcess, RetVal
            Sleep (100)
            DoEvents
        Loop While RetVal = STILL_ACTIVE
    End If
   
    CloseHandle hProcess
    WaitForProcess = RetVal

End Function
0
Comment
Question by:seckel
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12300363
Hi seckel,

Is the purpose of this question to determine how to poll a batch file for execution status, or is the end goal to simply copy x.txt  to y.txt?

You have a lot of advanced code to do a simple file copy!  =)

There are functions built into VB to copy a file.

~IM
0
 

Author Comment

by:seckel
ID: 12300517
This copy code will generate an errorlevel of 1.  

I need to know how to capture the errorlevel ( > 0) so I can trigger my VB application to stop instead of continue on.

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12300593
The errorlevel returned from the batch file will still be zero even if the copy command fails.  You can only check the errorlevel of a statement in a batch file, from within the batch file.

Why are you creating a batch file to do a simple file copy?

Just use the built in copy function in VB and check for errors:

    Private Sub Command1_Click()
        On Error GoTo FileCopyError
       
        FileCopy "x.txt", "y.txt"
        Exit Sub
       
    FileCopyError:
        MsgBox Err.Description, vbCritical, "Error " & Err.Number
    End Sub

~IM
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:seckel
ID: 12301014
I  didn't make it clear about the copy command...I am only using it to produce a desired errorlevel.

When I copy a file that exists, I force an errorlevel of 0 meaning the command was successful.

When I copy a file that does not exist,  I am forcing the batch file to return an errorlevel of 1, which means not successful. With the echo command, I can see that my copy command returns an errorlevel of 1.

Now I need to know how I can get my VB application to recognize the errorlevel, so that with any batch I chose to execute from the VB application, I can know if it worked or not worked and take appropiate action within my VB application.





0
 

Author Comment

by:seckel
ID: 12301035
"The errorlevel returned from the batch file will still be zero even if the copy command fails.  You can only check the errorlevel of a statement in a batch file, from within the batch file."

Are you saying there is now system code that VB can check to verify if the bat completed successfully or not?

Java and C can do it, I would think VB can also...
0
 
LVL 4

Expert Comment

by:AjithJose
ID: 12301046
The dos COPY command does not set ERRORLEVEL

If you want to get the results of a batch file operation the try redirecting the output into a txt file, and then check the file from VB

   Print #1,"@echo off"
    Print #1, ""
    Print #1, "copy x.txt y.txt"
    Print #1, ""
    Print #1, "IF ERRORLEVEL 1 ECHO FAILED > RESULT.DAT"
    Print #1, "exit"  
    Close #1

Then open the result.dat file from VB and check line failed

It is always better use alternate methods from VB or Windows API than depending on old DOS
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 12301080
Then as I said before:

The errorlevel returned from the batch file will still be zero even if the copy command fails.  You can only check the errorlevel of individual statements in batch files, from within the batch file itself.

From the point of view of a batch file, success simply means that it executed the commands contained within.  It doesn't care if those commands failed or not.

To trap the errorlevel you have echoed out would require to use pipes to redirect the standard IO stream to your VB app:
http://support.microsoft.com/default.aspx?scid=kb;en-us;173085

~IM
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12301107
AjithJoses method would certainly be simpler.

~IM
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to create a duplicate finder Application 9 127
Validating VB6 Function 19 68
MsgBox 2 61
Macro problems with Excel file 6 22
I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question