简体   繁体   中英

How can I verify directory in batch file after using chdir

Ok. I have this batch file that is designed to remove every file and folder from inside a folder that may or may not be present. The basic structure Follows:

@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)
)

The reason for the echoes in I'd like to be able to ensure the batch script has actually changed the path to MyDirectory and is deleting the correct files(we had an incident earlier that I'm kindof in hot water for where the script didn't change paths and deleted everything from one of our docs folders).

The echoes return the either the name of the batch file itself, or the path the batch file was run from,instead of "c:\\MyDirectory\\". So in my case it's from c:\\Testing\\ (a dummy directory I created to avoid a second oops).

Is there a way to get the currently active directory from inside a batch script, so that I can verify the directory I'm about to empty??

Try this:

@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)
)

Since you're in an if statement you should use setlocal EnableDelayedExpansion and use ! instead of % for variables.

To nuke the contents of a directory, use this shell script (batch file):

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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