batch script subroutine: Passing arguments

萝らか妹 提交于 2019-12-08 15:44:48

问题


My understanding is that in order to get the date from a file passed into a subroutine as an argument, you must re-set that argument as a variable within the subroutine. Is this correct? This doesn't make since to me, so I am wondering if I do not fully understand what is going on. I can use the passed in argument in practically any other subroutine code except for date extraction.

set setupEXE=setup.exe

CALL :SUB_CheckCorrectDate %setupEXE%
GOTO EOF
::----------------------------------

:SUB_CheckCorrectDate
set filename=%1%

:: SUCCESSFUL
for %%x in (%filename%) do set FileDate=%%~tx
@For /F "tokens=1-3 delims=-/ " %%A in ('@echo %FileDate%') do @( 
Set file_Month=%%A
Set file_Day=%%B
Set file_Year=%%C
)

:: GET ERROR    
for %%x in (%1%) do set FileDate=%%~tx
@For /F "tokens=1-3 delims=-/ " %%A in ('@echo %FileDate%') do @( 
Set file_Month=%%A
Set file_Day=%%B
Set file_Year=%%C
)    

GOTO:EOF

:: ------------------
:EOF

回答1:


Use %1 to access the parameter, not %i%.

The argument variables have the same modifiers as FOR variables, so you can use %~t1.

No need to execute a command in your FOR /F. It is simpler to process a string literal using in ("string").

No need for :EOF label. Every script has an implicit :eof. I like to use exit /b instead.

@echo off
setlocal
set "setupEXE=setup.exe"

call :SUB_CheckCorrectDate "%setupEXE%"
exit /b

::----------------------------------

:SUB_CheckCorrectDate
set "filename=%~1"
for /F "tokens=1-3 delims=-/ " %%A in ("%~t1") do ( 
  set "file_Month=%%A"
  set "file_Day=%%B"
  set "file_Year=%%C"
)
exit /b



回答2:


if you seriously want to write batch scripts, you should take care for the syntax:

@echo off &setlocal
set "setupEXE=setup.exe"

CALL :SUB_CheckCorrectDate "%setupEXE%"
GOTO EOF
::----------------------------------

:SUB_CheckCorrectDate
set "filename=%~1"

:: SUCCESSFUL
for %%x in ("%filename%") do set "FileDate=%%~tx"
For /F "tokens=1-3 delims=-/ " %%A in ("%FileDate%") do ( 
    Set "file_Month=%%A"
    Set "file_Day=%%B"
    Set "file_Year=%%C"
)

:: GET ERROR    
for %%x in ("%~1") do set "FileDate=%%~tx"
For /F "tokens=1-3 delims=-/ " %%A in ("%FileDate%") do ( 
    Set "file_Month=%%A"
    Set "file_Day=%%B"
    Set "file_Year=%%C"
)    

GOTO:EOF

:: ------------------
:


来源:https://stackoverflow.com/questions/19006067/batch-script-subroutine-passing-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!