获取 Windows 批处理文件中的最后一个命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5805181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:43:54  来源:igfitidea点击:

Get last command line argument in windows batch file

windowsbatch-file

提问by Jarek

I need to get last argument passed to windows batch script, how can I do that?

我需要将最后一个参数传递给 Windows 批处理脚本,我该怎么做?

回答by Random832

This will get the count of arguments:

这将获得参数的计数:

set count=0
for %%a in (%*) do set /a count+=1

To get the actual last argument, you can do

要获得实际的最后一个参数,您可以执行

for %%a in (%*) do set last=%%a

Note that this will fail if the command line has unbalanced quotes - the command line is re-parsed by forrather than directly using the parsing used for %1etc.

请注意,如果命令行具有不平衡的引号,这将失败 - 命令行被重新解析for而不是直接使用用于%1等的解析。

回答by Joey

The easiest and perhaps most reliable way would be to just use cmd's own parsing for arguments and shiftthen until no more are there.

最简单也可能是最可靠的方法是只使用cmd自己的参数解析,shift然后直到不再存在。

Since this destroys the use of %1, etc. you can do it in a subroutine:

由于这会破坏 等的使用%1,因此您可以在子例程中执行此操作:

@echo off
call :lastarg %*
echo Last argument: %LAST_ARG%
goto :eof

:lastarg
  set "LAST_ARG=%~1"
  shift
  if not "%~1"=="" goto lastarg
goto :eof

回答by mohan raj

set first=""
set last=""
for %%a in (%*) do (
SETLOCAL ENABLEDELAYEDEXPANSION
if !first!=="" (set first=!last!) else (set first=!first! !last!)
set last=%%a

)
ENDLOCAL & set "last=%last%" & set "first=%first%"
echo %last%  "and" %first%