如何从第N个位置获取批处理文件参数?

问题描述 投票:15回答:4

How to Pass Command Line Parameters in batch file之后,如何通过完全指定参数获得其余参数?我不想使用SHIFT,因为我不知道可能有多少参数,并且如果可以的话,我们希望避免对它们进行计数。

例如,给定此批处理文件:

@echo off
set par1=%1
set par2=%2
set par3=%3
set therest=%???
echo the script is %0
echo Parameter 1 is %par1%
echo Parameter 2 is %par2%
echo Parameter 3 is %par3%
echo and the rest are %therest%

运行mybatch opt1 opt2 opt3 opt4 opt5 ...opt20会产生:

the script is mybatch
Parameter 1 is opt1
Parameter 2 is opt2
Parameter 3 is opt3
and the rest are opt4 opt5 ...opt20

我知道%*给出了所有参数,但我不是前三个(例如)。

windows batch-file
4个回答
23
投票

以下是如何在不使用SHIFT的情况下执行此操作:

@echo off

for /f "tokens=1-3*" %%a in ("%*") do (
    set par1=%%a
    set par2=%%b
    set par3=%%c
    set therest=%%d
)

echo the script is %0
echo Parameter 1 is %par1%
echo Parameter 2 is %par2%
echo Parameter 3 is %par3%
echo and the rest are %therest%

1
投票

下面的代码使用shift,但它避免使用for解析命令行并让命令行解释器完成这项工作(考虑到for不能正确解析双引号,例如参数集A B" "C被解释为3个参数AB""Cfor,但由解释器作为AB" "C的2个参数;这种行为可以防止像"C:\Program Files\"这样的引用路径参数被正确处理):

@echo off

set "par1=%1" & shift /1
set "par2=%1" & shift /1
set "par3=%1" & shift /1

set therest=
set delim=

:REPEAT
if "%1"=="" goto :UNTIL
set "therest=%therest%%delim%%1"
set "delim= "
shift /1
goto :REPEAT
:UNTIL

echo the script is "%0"
echo Parameter 1 is "%par1%"
echo Parameter 2 is "%par2%"
echo Parameter 3 is "%par3%"
echo and the rest are "%therest%"
rem.the additional double-quotes in the above echoes^
    are intended to visualise potential whitespaces

%therest%中的其余参数可能看起来不像它们最初关于分隔符的方式(记住命令行解释器也将TAB,,;=视为分隔符以及所有组合),因为所有分隔符都被单个空格替换这里。但是,当将%therest%传递给其他命令或批处理文件时,它将被正确解析。

到目前为止我遇到的唯一限制适用于包含插入符号^的参数。其他限制(与<>|&"相关)适用于命令行解释器本身。


1
投票
@ECHO OFF
SET REST=
::# Guess you want 3rd and on.
CALL :SUBPUSH 3 %*
::# ':~1' here is merely to drop leading space.
ECHO REST=%REST:~1%
GOTO :EOF

:SUBPUSH
SET /A LAST=%1-1
SHIFT
::# Let's throw the first two away.
FOR /L %%z in (1,1,%LAST%) do (
  SHIFT
)
:aloop
SET PAR=%~1
IF "x%PAR%" == "x" (
  GOTO :EOF
)
ECHO PAR=%PAR%
SET REST=%REST% "%PAR%"
SHIFT
GOTO aloop
GOTO :EOF

我喜欢使用子程序而不是EnableDelayedExpansion。以上是从我的目录/文件模式处理批次中提取的。不要说这不能用=来处理参数,但至少可以用空格和通配符做引用的路径。


1
投票
@echo off
setlocal enabledelayedexpansion

set therest=;;;;;%*
set therest=!therest:;;;;;%1 %2 %3 =!

echo the script is %0
echo Parameter 1 is %1
echo Parameter 2 is %2
echo Parameter 3 is %3
echo and the rest are: %therest%

这适用于引用的参数和具有相同符号或逗号的参数,只要前三个参数没有这些特殊的分隔符字符。

样本输出:

test_args.bat "1 1 1" 2 3 --a=b "x y z"
Parameter 1 is "1 1 1"
Parameter 2 is 2
Parameter 3 is 3
and the rest are: --a=b "x y z"

这可以通过在原始命令行%1 %2 %3中替换%*来实现。前五个分号只是为了确保只替换第一次出现的这些%1 %2 %3

© www.soinside.com 2019 - 2024. All rights reserved.