Having an issue with if-else statements/error handling. Been trying to get this to work, cannot seem to do it. What I'm looking to do is have user input client id, then delete the directory associated with said client if it exists.


@echo off
set /p id=Enter ID:
rd /s /q "\\Images\Public on Images\DMS Scanned Clients\%id%"
echo \\Images\Public on Images\DMS Scanned Clients\%id%

So user would input 956862 for example. Then if directory at \Images\Public on Images\DMS Scanned Clients\956862 exists, it would be removed, otherwise, message would display stating it does not exist.


  • You do know that rd can only remove empty directories, right? to check if a file exists, you can use IF EXIST c:\test\file.txt To check if a folder exists, refer to the object NUL that always exists inside a folder even if its empty (according to Microsoft): IF EXIST c:\test\nul. But apparently in later windows versions where you use NTFS you can just use IF EXISTc:\test. – LPChip Aug 7 '15 at 13:17
  • Also, you have an error in your path. \\Images\Public on Images\ seems incorrect. The term on in a path is usually used to refer to a share ON a server. So make sure you have the server address correct or it will not work there either. – LPChip Aug 7 '15 at 13:18
  • Well, that's why I'm using the /s switch with RD, and the path is correct plus (and I'm not programmer, I'm a network guy) I think that since the path is all inside the quotes, it's not going to get hung up. – Zach Aug 7 '15 at 13:22
  • ah, missed the /s switch. – LPChip Aug 7 '15 at 13:23
  • Oh, and I tried IF EXIST command before posting the question, I'm not sure if my syntax was off, but it just wasn't executing correctly.... – Zach Aug 7 '15 at 13:56
@Echo off
pushd %1 >nul 2>&1  
If errorlevel 0 if not errorlevel 1 Echo %~nx1 is a folder
If errorlevel 1 Echo %~nx1 is not a folder

If /i "%cmdcmdline:~0,6%"=="cmd /c" pause

However in programming we do then test, not test then do. Testing requires a lot of system resources. Therefore to test then do requires two expensive disk accesses. Doing and testing the result (ie is the returned number 0) is only one disk access and a quick test of a number.

rd /s c:\somefolder && Echo Folder deleted || Echo Folder didn't exist

&& and || mean do if errorlevel is zero or not zero. It's easier than If errorlevel 0 if not errorlevel 1 echo errorlevel is 0 on multiple lines. See my post here Is typing %^ into cmd.exe a Windows easter egg?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.