繁体   English   中英

使用chdir后如何验证批处理文件中的目录

[英]How can I verify directory in batch file after using chdir

好。 我有此批处理文件,该文件旨在从可能存在或可能不存在的文件夹中删除每个文件和文件夹。 基本结构如下:

@echo off
If EXIST c:\MyDirectory\(
chdir c:\MyDirectory\

echo %CD%
echo %0
echo %~dp0

rem ... This removes everything from the folder....
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)

我希望能够确保批处理脚本实际上已将路径更改为MyDirectory并删除了正确的文件中的回显原因(我们之前曾发生过一次类似事件,因为我在脚本中没有这样做请勿更改路径,并从我们的docs文件夹之一删除所有内容)。

回显将返回批处理文件本身的名称,或者返回运行批处理文件的路径,而不是“ c:\\ MyDirectory \\”。 因此,就我而言,它来自c:\\ Testing \\(我创建的一个虚拟目录,以避免再次出现麻烦)。

有没有办法从批处理脚本中获取当前处于活动状态的目录,以便我可以验证要清空的目录?

尝试这个:

@echo off
setlocal EnableDelayedExpansion
If EXIST c:\MyDirectory\(
chdir c:\MyDirectory\

echo !CD!
pause

rem ... This removes everything from the folder....
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)

由于您使用的是if语句,因此应使用setlocal EnableDelayedExpansion并使用! 而不是%表示变量。

要核对目录的内容,请使用以下shell脚本(批处理文件):

@echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START

:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE

:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd

:DONE
endlocal

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM