Script blocks in CMD (advanced scripting no.2)

Well, I know I talked about this few times, but I decided to write more comprehensive article about this (this will follow previous about delayed expansion).

Many people think batches are stupid - I dont agree, I think you can do miracles with batches.

One of not really often used features are script block - I mean commands that are on more than one line. You can often see this:

If %Errorlevel% NEQ 0 Echo Error %ErrorLevel% occured!
If %Errorlevel% NEQ 0 FixError.cmd %ErrorLevel%
If %Errorlevel% NEQ 0 Goto EndOfScript

You can write this in more intelligent way:If %Errorlevel% NEQ 0 (
   Echo Error %ErrorLevel% occured!
   FixError.cmd %ErrorLevel%
   Goto EndOfScript
   )

And this is script block. You can use them either with If command or For command... And you can have many nested script blocks... For example this:

If %ErrorLevel% NEQ 0 (
   For /f "usebackq delims== tokens=1-2" %%i IN (`Set Error.`) Do (
      Echo Error %%j occured
      )
   Goto EndOfScript
)

Of course this is just example - you can make much MORE complex script blocks, for example some of mine are about 50 lines long (and when they are running, they create like 300 lines of code). When you get familiar with script block, you wont use common GoTo structure anymore - there is no need to.

But there is also one disadvantage - you must be advanced script write, because the script block is evaluated at beggining, so if you have some error, it is sometimes really hard to find out whats wrong.

 

Published Thu, Mar 30 2006 13:39 by martin
Filed under:

Comments

# re: Script blocks in CMD (advanced scripting no.2)

You can also "call" to labels just as if you were calling another batch file.
"Goto :EOF" can be used to "return" from such a call, or to exit a batch script. One should never use "exit" because it closes the command window you're running in.

Thursday, March 30, 2006 5:19 PM by Alun Jones

# re: Script blocks in CMD (advanced scripting no.2)

you can use && for connecting commands

If %Errorlevel% NEQ 0 Echo Error %ErrorLevel% occured! && FixError.cmd %ErrorLevel% && Goto EndOfScript

Saturday, January 12, 2008 10:43 AM by VasekB

# re: Script blocks in CMD (advanced scripting no.2)

2alunj: I prefer to use Exit - because if you use /b switch, it will exit (but not cmd, just script) and also return error level (for example Exit /b 1 will exit script with error level 1)

2VasekB: Well, it is not always possible - I have scripts where one line is expanded to 350 lines using script blocks ;)

Tuesday, January 29, 2008 1:43 PM by martin

# re: Script blocks in CMD (advanced scripting no.2)

I still prefer using GOTO and such.  You can make all the feedbacks you need for errors and then GOTO them when needed (using a variable holding the label name to continue on to so you can let the script jump back to the right place afterwards).

Monday, November 10, 2008 3:59 PM by veltas