批处理文件参数处理

时间:2015-03-31 11:01:47

标签: batch-file command-line-arguments

假设我有一个名为check.bat的批处理文件。我使用命令

在java上运行它
Runtime.getRuntime().exec("cmd /c start C:\\check.bat");

它运行批处理文件没有问题。但是当我将参数传递给批处理文件时,

  

Runtime.getRuntime()。exec(“cmd / c start C:\ check.bat arg1 arg2 arg3 arg4”);

我想在check.bat中访问这些参数 我知道%*让我得到了所有的论据。但我想要的是除了最后一个参数作为单个变量之外的所有参数。 批处理文件非常新。请帮忙。

2 个答案:

答案 0 :(得分:0)

通常,您可以将前三个参数作为一个巨大的参数,将它们放在check.bat "arg1 arg2 arg3" arg4

之类的引号中

由于这是在Java中,您应该能够将一些引号转义为exec命令,例如Runtime.getRuntime().exec("cmd /c start C:\check.bat \"arg1 arg2 arg3\" arg4");

如果出于某些原因无效,您可以随时批量处理这四个参数,并在批处理脚本中对它们执行任何操作。

@echo off
set first_three="%1 %2 %3"
set last_one=%4

答案 1 :(得分:0)

SomethingDark建议的第一种方法(在调用批处理文件之前将参数组合在一起)可能是最好的,但如果您无法使用它,则以下内容可能有所帮助(如果您需要,可能需要进行实验)参数包含对Windows具有特殊含义的字符:

@echo off
        setlocal
        set ALLBUT1=
        if "%~2" == "" goto :gotthem
        set ALLBUT1=%1
:loop
        shift
        if "%~2" == "" goto :gotthem
        set "ALLBUT1=%ALLBUT1% %1"
        goto :loop
:gotthem
        set "LAST=%1"

        echo All-but-one:%ALLBUT1%:
        echo Last:%LAST%:

给出:

S:\>arg one two three
All-but-one:one two:
Last:three:

S:\>arg one two three four
All-but-one:one two three:
Last:four: