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.