The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Sep 2008»»
SMTWTFS
 
1
2
3
456
78910111213
14151617181920
21222324252627
282930

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Setting the DOS ErrorLevel

posted Monday, 21 November 2005

Programs can return an errorLevel. Batch scripts can then access than using %ErrorLevel%, and then use this in the flow of the script. For example, if program X returns a certain errorLevel, the script can take a specific path. Convention is that an errorLevel of 0 is "Success", and anything else is some kind of failure.

This is not to be confused with creating an environmental variable named "ErrorLevel". Setting the environmental variable does not update the batch script's error level itself. This becomes apparent when using another tool that checks the script errorLevel. For example, in NAnt you can execute batch scripts and specify the build to fail if there's an error in the batch. However, you'll notice (at least in version .84) that setting the errorLevel as an environmental variable won't cause the script to fail, but having an exe fail will.

We want the option of setting the errorLevel from an environmental variable, not just through an exe. We can do this by writing a trivial console app:

[STAThread]
static int Main(string[] args)
{
      int i = 0;
      try
      {
         i = Convert.ToInt32(args[0]);
      }
      catch
      {
        Console.WriteLine("Error info...");
      }
      return i;
}

This takes a single argument from the command line, converts it to an integer, and then returns that value as the program error code. Note that console apps need not return "void", as is the template default. They can return int precisely for this purpose.

We can then call this program, passing in some parameter from DOS, and it will set the errorLevel. You'll notice that this would cause the NAnt build to fail. Also note that this call must be the every last line of the batch - not even an ECHO or REM after it.

Confusing the environmental errorLevel and DOS script's errorLevel is an easy and understandable mistake, and fortunately it has an easy and understandable solution.

links: digg this    technorati    




1. Kurt left...
Thursday, 17 August 2006 3:14 pm

Great idea - just for convenience it might be nice to just post the exe for the simple program here.