none
Variables Work Until Put Inside If Statement RRS feed

  • Question

  • I'm trying to add some code to a batch file that I have first by writing a separate batch file. The batch file is to ask the user if they need to copy data from one location to another. It works when I just create the code for copying the files, but when I add an if statement letting the user decide whether or not to copy files the value for the variable that sets the source path becomes empty.

    Code without if statement that works

     
     cls
     echo.
     set /p UserData=Enter path of the data to be restored:%=%
     Echo the value you added was %UserData%
     echo.
     md c:\Backup\
     Echo the value you added was %UserData%
     robocopy %UserData% c:\Backup

    When I add the if statement for user to decide whether or not to copy files.

    @echo off
    
    set /p RestoreData=Do you have user data to restore? (y or n):%=%
    
    if %RestoreData%==y (
    	cls
    	echo.
    	set /p UserData=Enter path of the data to be restored:%=%
    	Echo the value you added was %UserData%
    	echo.
    	md c:\Backup\
    	Echo the value you added was %UserData%
    	robocopy %UserData% c:\Backup
    	) 
    	Else If (
    	echo No user data to be copied at this time.
    	)
    
    
    pause

    Now the variable UserData is empty. robocopy sees the c:\backup as the source and a blank for the destination as it is not seeing the UserData variable.

    This is being written in notepad as a .bat file. Anyone have any suggestions?

    Thank you. 

    Sunday, February 2, 2014 7:21 PM

Answers

  • Environment variables (in between % characters) are expanded when the line of code is parsed, not when it is executed.

    Cmd considers the code in parentheses ( ) to be a single line.

    To work around this behavior, use setlocal enabledelayedexpansion at the top of your script, and use ! instead of % for the environment variable names in the code in the parentheses.

    Type cmd /? at a command prompt and read carefully (pay particular attention to references to delayed variable expansion) for more information.

    Bill

    Sunday, February 2, 2014 11:24 PM
    Moderator