views:

44

answers:

3

I have a batch file and I need to invoke it like this "mybatch.bat -r c:\mydir", and the batch file loops through the directory and writes file names to the output. The problem I'm facing is that I cannot read parameter "-r".

Here's what it looks like:

@echo off
echo [%date% %time%] VERBOSE    START
for %%X in (%1\*.xml) do echo [%date% %time%] VERBOSE    systemmsg Parsing XML file '%%X'
echo [%date% %time%] VERBOSE    END

I can however use %2 instead of %1 and all works fine, but I want to read by parameter. Is this possible?

Cheers!

+3  A: 

I'm not entirely sure I see your problem. %1 in this case is clearly -r and you should be using %2 which is c:\mydir.

If you mean you want to ensure that the user specifies -r first, you can use something like:

@echo off
if not "x%1"=="x-r" (
    echo [%date% %time%] ERROR Called without -r
    goto :eof
)
echo [%date% %time%] VERBOSE    START
for %%X in (%2\*.xml) do echo [%date% %time%] VERBOSE systemmsg Parsing file '%%X'
echo [%date% %time%] VERBOSE    END

If the -r is optional, you can often do:

set fspec=%1
set rflag=no
if "x%fspec"=="x-r" (
    set fspec=%2
    set rflag=yes
)

and then use rflag and fspec.

Doing true position-independent parameter parsing in batch is not an easy job. We have a subsystem which does it but unfortunately, it's proprietary. I will tell you it runs across about 80-odd lines and is not the fastest beast in the world.

My advice would be to impose strict requirements of the argument formats rather than go down the position-independent path. You'll save yourself a lot of hassles :-)

paxdiablo
Looks great. Thank for the advice as well!
Ostati
A: 

Why can't you call your batchfile simply as mybatch.bat c:\mydir, then just evaluate %1, and be done?

pipitas
I'm writing unit tests to simulate what the real command does as I need to read and parse the output. Thanks!
Ostati
A: 

If the only purpose of the batchfile is to write the filenames to output, can't you simply use dir /b /s ?

pipitas