0

I have the following code snippet:

   @echo off 

for %%d in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
  if exist "%%d:\Program Files (x86)\location\folder" (
    cd /d "%%d:\Program Files (x86)\location\folder"
  ) else cd /d "%%d:\location\folder\" 2>nul && goto :break

)

::display error message if folder not found
:break
if %errorlevel% equ 0 (
    echo "Folder found, going to folder location"
) else (
    set /p location=Could not find folder. Please enter folder location: 
    cd %location%
    echo %location%
)

For some reason, when I give it location to CD to, the first time it CDs to the wrong file location. If I run the code snippet again from the same command line, it CDs to the previously given file location. Any reason this could be?

Violet Smith
  • 3
  • 1
  • 4

1 Answers1

0

you need delayed expansion:

::display error message if folder not found
:break
setlocal enableDelayedExpansion
if %errorlevel% equ 0 (
    echo "Folder found, going to folder location"
) else (
    set /p location="Could not find folder. Please enter folder location: "
    cd /d "!location!"
)

better use cd with /d switch if there's a chance of drive jumping

EDIT try this (not tested):

   @echo off 

for %%d in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
  if exist "%%d:\Program Files (x86)\location\folder" (
    cd /d "%%d:\Program Files (x86)\location\folder"
  ) else (
    cd /d "%%d:\location\folder\" 2>nul && goto :break
  )

)


for %%d in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
  if exist "%%d:\Program Files (x86)\location\folder" (
    cd /d "%%d:\Program Files (x86)\location\folder"
    goto :break
  )
)

for %%d in (c d e f g h i j k l m n o p q r s t u v w x y z) do (
  if exist "%%d:\location\folder\" (
    cd /d "%%d:\location\folder\"
    goto :break
  )
)

:retry
set /p "location=Could not find folder. Please enter folder location: "
cd /d "%location%"  2>nul || (
  echo wrong location
  echo try again
  goto :retry
)
echo %location%
goto :break



::display error message if folder not found

echo "Folder found, going to folder location"

exit /b 0
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • When I use this version, it jumps to 'folder found...' even if the folder is not found. – Violet Smith May 06 '15 at 14:14
  • @VioletSmith What's in the rest of your code? Here's there's nothing that could tell me what and how sets the error level – npocmaka May 06 '15 at 14:22
  • @VioletSmith - check also this - http://stackoverflow.com/questions/15885132/file-folder-chooser-dialog-from-a-windows-batch-script – npocmaka May 06 '15 at 14:27