问题
I am trying to create a batch script which would perform the same action for each parameter given. For example, giving X files as parameters:script.bat "file1.txt" "file2.txt" "file3.txt" "file4.txt" ... "fileX.txt"
will rename them to:"file1.bin" "file2.bin" "file3.bin" "file4.bin" ... "fileX.bin"
Rename is just an example, I will need it for more complex operations too.
I guess it should be something like for each but I'm new in batch scripts.
I just wonder if I could just increment %1 index...
回答1:
You can use SHIFT to shift the parameters left. In other words calling shift will put the second parameter to %1, the third to %2 etc.
So you need something like:
@ECHO OFF
:Loop
IF "%1"=="" GOTO Continue
ECHO %1
SHIFT
GOTO Loop
:Continue
This will just print the arguments in order, but you can do whatever you want inside the loop.
回答2:
You can do something like this and just add the complexity you want:
for %%x in (%*) do (
echo %%x
)
回答3:
What I ended up with was the following. I tend to over do things, thought I would share...
At the top of my batch file I have the following code...
Usage:
::--------------------------------------------------------
:: Handle parameters
::--------------------------------------------------------
CALL:ChkSwitch bOverwrite "/OVERWRITE" %*
CALL:ChkSwitch bMerge "/MERGED" %*
Then at the bottom (where I usually place all my functions)...
Function:
::--------------------------------------------------------
:: ChkSwitch Function
::--------------------------------------------------------
:ChkSwitch <bRet> <sSwitch> <sParams> (
SETLOCAL EnableDelayedExpansion
SET "switched=0"
:ChkSwitchLoop
IF "%~3"=="" GOTO ChkSwitchDone
IF %~3==%~2 (
SET "switched=1"
GOTO ChkSwitchDone
)
SHIFT /3
GOTO ChkSwitchLoop
:ChkSwitchDone
)
(
ENDLOCAL
SET "%~1=%switched%"
EXIT /B
)
To use this its simple. You just call the function passing in a variable you wish to change OR create than next pass the switch you are looking for and last pass all the params from the script.
来源:https://stackoverflow.com/questions/9457355/batch-parse-each-parameter