Search code examples
batch-fileerror-handlingcmdxcopyrobocopy

Allow Bat Script to act upon error


I have a bat file that creates a folder and sub-folders based on a user input. I would like the code to tell me a folder it is trying to create already exists, and furthermore (if possible), if the folder already exists, I would like the code to copy the sub-folders into the pre-existing folder.

My code -

@echo off
echo.
:EnterName
set "dest=""
set /P "dest=Enter Name: "
set "dest=%dest:"=%"
if "%dest%" == "" cls & goto EnterName

set "findest=Z:\ProjectIT\copy\%dest%"

robocopy Z:\ProjectIT\copy\xcopy "%findest%" /e /NFL /NDL /NJH /NJS

echo Construction folder has been created for "%dest%"
echo.

pause

Hope that makes sense!


Solution

  • The command you are looking for is if exist:

    @echo off
    echo.
    :EnterName
    set "dest=""
    set /P "dest=Enter Name: "
    set "dest=%dest:"=%"
    if "%dest%"=="" cls & goto EnterName
    
    if exist %findest% (
        echo This folder already exists!
        echo All subfolders will be copied to the existing folder.
    )
    
    set "findest=Z:\ProjectIT\copy\%dest%"
    
    robocopy Z:\ProjectIT\copy\xcopy "%findest%" /e /NFL /NDL /NJH /NJS
    
    echo Construction folder has been created for "%dest%"
    echo.
    
    pause
    

    You don't have to modify the code to copy the subfolders. If the folder exists, everything will be copied into it.