batch-filewindows-xpwindows-embedded

Adding if exist to an existing batch file


I am trying to add additional functionality to an existing batch file, the below snippet of code copies my data from one location to another and then deletes the zip file that was created, all works well.

what I want to do is if the file already exists on the USB drive to add an incremental number to the end of the file eg. FileName-FileDate(1) or FileName-FileDate(2) I could add time to the FileStamp which at the moment adds the date but this could make the file name a bit long.

I am copying the file to a USB drive as a backup, this is why I am using drives E, F, G, H, dependant in what Windows sees the drive as, it is also important that the created file on the C: drive is deleted due to space.

I am using the /y to reduce user input as it will be done by people with limited technology skills so I don't really want to use /-y. also the machine does not have a keyboard, only a touch screen, so renaming the file is not an easy thing to do.

REM ------ Creation of the ZIP file ------

%SupervisorPath%\7-ZipPortable\App\7-Zip\7z a -tzip %BackupPath%\Backup\%FileStamp%.zip %BackupPath%\Backup\


REM ------ Copy the backup file to a USB drive with File Name and Date Stamp ------

IF EXIST E: (echo copying files to USB drive E:
             copy %BackupPath%\Backup\%FileStamp%.zip E: /y )
IF EXIST F: (echo copying files to USB drive F:
             copy %BackupPath%\Backup\%FileStamp%.zip F: /y )
IF EXIST G: (echo copying files to USB drive G:
             copy %BackupPath%\Backup\%FileStamp%.zip G: /y )
IF EXIST H: (echo copying files to USB drive H:
             copy %BackupPath%\Backup\%FileStamp%.zip H: /y )

REM ------ Delete the temporary zip file from the backup folder ------           

echo Deleting temporary zip file from the backup folder

Del %BackupPath%\Backup\%FileStamp%.zip

Solution

  • IF EXIST does not work on drive letters and directories, but fortunately, there is an obscure workaround:

    C:\> IF NOT EXIST D:\NUL ECHO D:\ not present.
    D:\ not present.
    C:\> IF EXIST C:\NUL ECHO C:\ exists.
    C:\ exists.
    

    It turns out that to support constructs like appending >NUL on command statements, there is a sort of virtual file named "NUL" in every directory including the root directory of a drive. Checking for its existence is equivalent to a check for the directory or drive's existence.

    This behavior is documented in a Microsoft knowledge base article ( https://support.microsoft.com/en-us/kb/65994 ) and I have confirmed its behavior on FreeDOS 1.1 and in a Windows 7 command shell.

    Though the KB article addresses checking for directory existance, it also indicates the technique can be used to see if a drive is present. In the case of checking for drive existence, however, caveats exist: