提示目录和md与.bat文件

时间:2016-02-18 16:08:24

标签: batch-file command-line cmd cd

我正在制作一个bat文件,提示用户输入目录并在该提示目录中创建目录

@echo off
set /p dir=enter directory: 
cd %dir%
cd
md assets
cd assets

md folder folder2 folder

md addons
cd addons

md folder folder2 folder

我把这个文件放在桌面上,所以当我运行这个文件时,一切都发生在桌面上,而不是我提示的目录。我该怎么办?

1 个答案:

答案 0 :(得分:2)

第一个建议:删除(或注释掉)@echo off,以便在运行时看到它正在做什么。这可能会立即明确为什么它不能按预期工作。一旦按照自己的方式运行,请重新添加@echo off

第二条建议:您可能需要进行一些验证,以确保您的%dir%可用于cd命令。例如,如果%dir%目录实际上不存在,则cd命令将失败。或者,如果您的输入包含驱动器号(例如E:\newFolder\),除非您使用cd开关,否则/d命令将无法将您带到那里。

第三条建议:最好将路径名和路径变量放在引号中,如下所示:

set /p "dir=enter directory:"

这是我更喜欢的替代方法,即完全避免批处理文件中的cd。抛出一些输入验证。

:SetDriveLetter
set /p "drive=enter drive letter:"
:: check for colon following drive letter, add it if it's not there
:: (add whatever other input validation you think necessary)
if not "%drive:~1%"==":" set drive=%drive%:
if not exist "%drive%\" (
    echo invalid drive. 
    goto SetDriveLetter
)
:SetDirectory
set /p "dir=enter directory:"
:: check for backslash preceding the directory, remove it if it's there
:: (add whatever other input validation you think necessary)
if ^%dir:~0,1%==^\ set dir=%dir:~1%
echo This will create folders in %drive%\%dir%\  
choice /m "Continue with this operation?"
if errorlevel 2 (
    echo Operation cancelled by user.
    goto End
)
:: You can use the `md` command to create multiple directories in one line.
:: I prefer to separate them out, one per line, for better readability.  
md "%drive%\%dir%\assets
md "%drive%\%dir%\assets\folder" 
md "%drive%\%dir%\assets\folder2" 
md "%drive%\%dir%\assets\addons"
md "%drive%\%dir%\assets\addons\folder" 
md "%drive%\%dir%\assets\addons\folder2"

:End