Search code examples
batch-fileargumentsargument-passingsubroutine

batch script subroutine: Passing arguments


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

Solution

  • 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