批量读取命令行参数时设置变量

时间:2015-01-29 16:53:55

标签: batch-file command-line command-line-arguments

我正在编写一个脚本来打开我们的开发人员通常通过命令行和浏览器一直访问的文件夹。现在这就是它的样子:

@echo off

if "%~1" == "" goto noargs
if "%~1" == "/h" goto noargs
if "%~1" == "common1" goto setcommon1
if "%~1" == "common2" goto setcommon2
REM other folders here...

if "%~2" == "-t" (
    set OPENINCMD=1
) else (
    set OPENINCMD=0
)

REM This is where noargs is but I removed it for brevity

:setcommon1
set FOLDERPATH="C:\Users\username\common folder 1"
goto execute
:setcommon2
set FOLDERPATH="C:\Users\username\CommonFolder2"
goto execute

:execute
if %OPENINCMD% EQU 1  (
    cd %FOLDERPATH%
) ELSE (
    explorer.exe %FOLDERPATH%
)

但我希望能够设置%FOLDERPATH%变量,因为我在开始时通过命令行参数进行解析。

在设置变量时,我尝试使用setlocal enableextentsions enabledelayedexpansion并使用!FOLDERPATH!代替%FOLDERPATH%代替FOLDERPATH代替!FOLDERPATH!。我也试过在两个地方使用endlocal而没有运气。我的文件末尾也有FOLDERPATH

这就是我想象的样子,但这不会在运行时设置... if "%~1" == "" goto noargs if "%~1" == "/h" goto noargs if "%~1" == "common1" set FOLDERPATH="C:\Users\username\common folder 1" if "%~1" == "common2" set FOLDERPATH="C:\Users\username\CommonFolder2" ... 变量。

{{1}}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

乍一看至少有两个错误:

  • 引用set
  • 未在OPENINCMD
  • 定义:execute

这可行:

rem ... your code here 
rem goto :anypoint
goto :eof

:setOPEN
if "%~2" == "-t" (
    set OPENINCMD=1
) else (
    set OPENINCMD=0
)
goto :eof

REM This is where noargs is but I removed it for brevity

:setcommon1
set "FOLDERPATH=C:\Users\username\common folder 1"
goto execute
:setcommon2
set "FOLDERPATH=C:\Users\username\CommonFolder2"
goto execute

:execute
call :setOPEN
if %OPENINCMD% EQU 1  (
    cd "%FOLDERPATH%"
) ELSE (
    explorer.exe "%FOLDERPATH%"
)