Mostly Linux & Python syntax notes and hyperlinks.

Thursday, December 4, 2014

Windows Batch Script: Collecting Y/N inside FOR loop via subroutine

In Windows scripting, any variable such as %yn% is expanded before a FOR loop is activated.

To collect data inside a FOR loop you need to do two things:
  1. Use ! ! around your variable instead of % %
  2. At the top of the file: setlocal enabledelayedexpansion 
REM next line needed for !yn! to work: 
setlocal enabledelayedexpansion  

@echo off 
FOR %%G IN (a,b) DO (
    echo how about %%G? 
    call :YorN
    if !yn!==Y ( 
        echo yes
        call :eab %%G 
    ) else (echo no) 

pause 
goto:EOF 

:YorN
    echo Y or N
    set /P yn=Y/N:
    IF /I %yn%==y(
        set yn=Y
    ) ELSE (
        set yn=N
    )
    echo YorN %yn%
    goto:EOF
:EOF 

References:

http://stackoverflow.com/questions/2514476/the-value-returned-from-a-function-in-a-windows-batch-script-is-ignored-in-a-for
http://stackoverflow.com/questions/12021033/how-do-i-ask-a-for-user-input-and-receive-user-input-in-a-bat-and-use-it-to-run
http://ss64.com/nt/if.html

No comments:

Post a Comment