在批处理文件中查找命令行参数的值 [英] Find value of command line argument in batch file

查看:85
本文介绍了在批处理文件中查找命令行参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行批处理文件时传递了参数列表,并且需要特定参数-logdir的值来在我的批处理文件中设置一些dir路径.我如何首先检查 -logdir 是否作为参数传递,以及是否传递它获取其值并将其设置在变量中.

I am passing a list of arguments while running a batch file and need the value of a particular argument -logdir to set some dir path in my batch file. How can I first check if the -logdir is passed as argument and if it is passed get its value and set it in a variable.

我的运行方式如下:

test.bat -env test1 -logdir C:\Users\...\log -userhome ... -log ...

以及更多其他参数.这些参数可以按不同顺序传递.

and many more arguments. These arguments can be passed in different order.

我能够获取使用下面传递的参数列表.

I am able to fetch the list of arguments passed using below.

set argCount=0
for %%x in (%*) do set /A argCount+=1
echo Number of processed arguments: %argCount%
set /a count=0
for /l %%x in (1, 1, %argCount%) do (
  set /a count=!count!+1
  call set "var=%%!count!"
  echo var= %!var!
)

但是我在将这个args与值进行比较时遇到了问题.我尝试使用if,如下所示:

But I am facing issues comparing this args with the value. I tried using if as below :

if -> if "!_var!" equ "-logdir" set /a logdir="%%!count!"

但是由于语法错误而出现错误.

But getting error as syntax not correct.

推荐答案

您声称可以存在更多参数".%x 语法只能使用前九个参数,因此,在可用的%1 %9 的情况下,您只能处理四对,其中可能太少了.令人高兴的是,参数10 ...不会丢失(尽管不能直接访问).您可以将参数列表向左移动.

You claim there can be "many more arguments". The %x syntax can only use the first nine parameters, so with the available %1 to %9 you can only process four pairs, which might be too few. Gladly, the parameters 10... are not lost (although not directly accessible). You can shift the parameter list to the left.

由于参数对可以以不同的顺序传递",因此最好仅将偶数参数(值)分配给像奇数参数(变量)这样命名的变量.我在代码中添加了一些REM来进行解释:

As the parameter pairs "can be passed in different order", it's best to just assign the even parameters (values) to variables named like the odd parameters (variables). I addes some REM's to the code to explain it:

@echo off & setlocal
:loop
if "%~2" == "" goto :done  & REM if no other pair of parameters then done
set "%~1=%~2" & REM set variable
shift & REM remove first...
shift & REM ... two params
goto :loop  & REM and repeat
:done
REM show parameters:
set -

注意:不进行语法检查.参数应重复为 -param value

Note: no syntax check. Parameters are expected to be repeatedly -param and value

要传递带有空格(或其他定界符)的参数,请像使用引号一样

To pass parameters with spaces (or other delimiters), quote them like

test.bat -env test1 -logdir "C:\path with spaces\log"

这篇关于在批处理文件中查找命令行参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆