0

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.

Code:

@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%
pause

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.

Thanks

Zach
  • 1
  • 1
  • 1
  • 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 07 '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 07 '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 07 '15 at 13:22
  • ah, missed the /s switch. – LPChip Aug 07 '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 07 '15 at 13:56
  • proper IF Exist: `IF EXIST "c:\test" echo works` and echo works can be substituted for `goto a` (which goes to the label `:a` in your script. – LPChip Aug 07 '15 at 14:36
  • ah, i was missing the quotations....thank you so much – Zach Aug 07 '15 at 15:17

1 Answers1

0
@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
Popd

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?

bill
  • 31
  • 2