variable - write windows script
如何從第N個位置獲取批處理文件參數? (3)
下面是你如何做到這一點,而不使用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%
關於如何在批處理文件中傳遞命令行參數進一步如何得到剩下的參數並精確地指定它們? 我不想使用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
我知道%*
給出了所有的參數,但是我不想要前三個(例如)。
但在這裡你知道會有多少人。 你知道你會有三個。 移動三次,剩下的參數都是 %*
。也就是說,當你使用 shift
,你改變 %*
的表觀值來表示你還沒有關閉的參數。
@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
。 以上是從我的目錄/文件模式處理批次中提取的。 不要說這個不能用=
來處理參數,但是至少可以用空格和通配符做引用的路徑。