批处理文件参数处理



假设我有一个名为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中的这些参数我知道%*会引起我所有的争论。但我想要的是所有的参数,除了最后一个作为单个变量的参数。批处理文件非常新。请帮忙。

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:

通常,您可以将前三个参数作为一个巨大的参数,方法是将它们放在像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

最新更新