批处理脚本如何传递多个参数进行调用

3
我已经编写了一个脚本,其中包含一个函数,该函数应循环遍历列表,并返回给定列表中项目的索引的值。我有一个名为::find 的函数,它应该接受两个参数:列表和项位置。我不确定如何处理函数中的多个参数。如果我在循环中用%MY_LIST%替换%LIST%,并从传递给call :find的参数列表中删除%MY_LIST%,则此脚本可以正常运行,但我真的想知道如何传递多个参数。我认为它们只是作为一个整体字符串传递到函数中...
@echo off
setlocal enableDelayedExpansion
cls

:: ----------------------------------------------------------
:: Variable declarations
:: ----------------------------------------------------------
set RETURN=-1
set MY_LIST=("foo" "bar" "baz")
set TARGET_INDEX=1

:: ----------------------------------------------------------
:: Main procedure
:: ----------------------------------------------------------
call :log "Finding item %TARGET_INDEX%..."
call :find %MY_LIST% %TARGET_INDEX%
call :log "The value is: %RETURN%"
goto Exit

:: ----------------------------------------------------------
:: Function declarations
:: ----------------------------------------------------------
:find
call :log "Called `:find` with params: [%*]"
set /a i=0
set LIST=%~1 & shift

for %%a in %LIST% do (
    if !i! == %~1 (
        set RETURN=%%a
    )
    set /a i=!i!+1
)
goto:EOF

:printDate
for /f "tokens=2-4 delims=/ " %%a in ('echo %DATE%') do (
  set mydate=%%c/%%a/%%b)
for /f "tokens=1-3 delims=/:./ " %%a in ('echo %TIME%') do (
  set mytime=%%a:%%b:%%c)
echo|set /p="[%mydate% %mytime%] "
goto:EOF

:log
call :printDate
echo %~1
goto:EOF

:: ----------------------------------------------------------
:: End of script
:: ----------------------------------------------------------

:Exit

更新

我的脚本现在已经运行正常,感谢nephi12的帮助。 http://pastebin.com/xGdFWmnM

3个回答

6
call :find "%MY_LIST%" %TARGET_INDEX%
goto :EOF

:find
echo %~1 %~2
goto :EOF

他们作为参数传递给脚本...;)

可以,谢谢。但是你知道它为什么有效吗?另外,这是我的工作脚本!http://pastebin.com/xGdFWmnM - Mr. Polywhirl
1
将“'s pass it as one parameter, quotes and all. the ~ in %~1 removes quotes if they are there.”翻译成中文。仅返回翻译后的文本。 - cure
脚本看起来很棒!它组织得很好,而且效率高。 - cure
此解决方案仅限于列表中的9个值。 - dbenham

4
下面是针对空格分隔值列表的索引查找另一种方法。定义列表时不要使用括号。单词无需加引号。包含空格、制表符、分号或等号的短语必须用引号括起来。还有像&|这样具有特殊字符的值也应该用引号括起来。
然后反转:FIND参数的顺序——先是索引,然后是实际列表。在FOR/L循环中使用SHIFT将所需的索引值传递给第一个参数。
该解决方案的一个优点是,只要它们适合每行8191个字符的限制,就可以支持任意数量的值。nephi12解决方案仅限于9个值。
@echo off
setlocal
set MY_LIST=foo bar baz "Hello world!"
call :find %~1 %MY_LIST%
echo return=%return%
exit /b

:find  index  list...
for /L %%N in (1 1 %~1) do shift /1
set "return=%~1"
exit /b

2

尝试这个,我认为它能回答你的问题。将其放在批处理文件中,在看到它工作后构建其他所需内容。用带引号的字符串从命令提示符执行它:YourBatFile "Arg1 Arg2 Arg3 Etc"

@echo off
call :DoSomethingWithEach %~1
goto :eof

:DoSomethingWithEach
for %%a in (%*) do echo.%%a
goto :eof

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接