Search code examples
batch-filewindows-10file-exists

Windows 10 batch file - test if directory exists, copy file, beep on error


I've been looking at many posts on this site to see what I'm doing wrong, but I can't get this simple script to work.

The script is stored in my %MyDocuments%\IT\scripts\ folder, which is in my PATH. I CD to the folder that I want to run the script from then call it and pass a photo number, i.e.

r5 0893

If the folder .\Rejects does not exist, I need to create it. Then it tries to move the file to the Rejects subfolder, and I'd like to beep if the copy failed, e.g. I've put in a photo number that doesn't exist.

:: echo off
if exist Rejects 
(
    echo Rejects\ found, goto DirectoryExists
    goto DirectoryExists
)
else
(
    echo Creating Rejects\ folder
    mkdir Rejects 
)
:DirectoryExists
:: pause
echo if not exist 2X9A%1.jpg
if not exist 2X9A%1.jpg
(
    echo "File 2X9A%1.jpg not found!!!"
    rundll32 user32.dll,MessageBeep
)
Else
(
    echo move 2X9A%1.jpg To Rejects\
    move 2X9A%1.jpg Rejects\
)
:: pause

Furthermore, these commands work one at a time from the command prompt, but not from the batch file! :

D:\Photos\2018\1.06. Leyla>r5 0489
The syntax of the command is incorrect.
D:\Photos\2018\1.06. Leyla>if exist Rejects
D:\Photos\2018\1.06. Leyla>if exist Rejects echo Yes
Yes

What am I doing wrong??

Thanks for your help!


Solution

  • Your code has to be fixed like this:

    @echo off
    
    if exist Rejects (
        echo Rejects\ found, going to DirectoryExists
        goto DirectoryExists
    ) else (
        echo Creating Rejects\ folder
        mkdir Rejects 
    )
    
    :DirectoryExists
    rem pause
    echo if not exist 2X9A%1.jpg
    
    if not exist 2X9A%1.jpg (
        echo "File 2X9A%1.jpg not found!"
        rundll32 user32.dll,MessageBeep
    ) else (
        echo move 2X9A%1.jpg To Rejects\
        move 2X9A%1.jpg Rejects\
    )
    
    pause
    

    You seem to program in low/medium level languages. However, this is the default syntax for if in batch file.

    Type if /? in cmd.exe to learn more about its syntax.