我有以下代码段:
@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%
)
出于某种原因,当我把它放到CD的位置时,它第一次将CD送到错误的文件位置。如果我从同一命令行再次运行代码片段,它将CD转到先前给定的文件位置。这可能是什么原因?
答案 0 :(得分:0)
::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!"
)
如果有机会跳跃,可以更好地使用带/d
开关的cd
编辑试试这个(未经测试):
@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