开发者

Using switches inside batch file

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 fil开发者_运维技巧e 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!


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 :-)


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜