Julian White
Julian White

Reputation: 1753

Issue dynamically finding a USB and backing up to it?

need some help with coding, I'm trying to write a bat file that, when fired, will look for a USB drive and then copy a directory to it. And if the USB isn't plugged in, it will sit and wait for the user to plug it in. Here's the code I have so far:

@echo off 
COLOR 70
@title Finding and Backing Up
@echo Please plug in your USB.

:Find
for %%a in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
IF EXIST %%a:\backupusb.id SET %%USBDRV=%%a: && GOTO UniTest:
)
GOTO :Find

echo I will look for your work and ensure it's backed up against the USB's Database, please wait.

:UniTest
IF EXIST "%USERPROFILE%\Documents\University" (
echo Found University work, please wait while it's backed up.
xcopy "%USERPROFILE%\Documents\University" "%USBDRV%\Backups\University" /S /D /Y /I /E > nul
echo University work located and successfully backed up.
GOTO End:
) ELSE (
echo I could not find any University folder in your Documents folder
GOTO End:
)

:exit
echo Done!

The only issue is, I'm still relatively derpy when it comes to coding, and while it sits on 'please plug in your USB' correcty, as soon as the USB is plugged in it continues with the script however it will dump it to a random HDD, usually C:/. I can't seem to figure out where I went wrong, knowing my luck it's something damn small.

Any advice or solutions? Much appreciated! Thanks -Julian

Upvotes: 0

Views: 68

Answers (2)

Hunt IT
Hunt IT

Reputation: 131

One minor change to how you set the USBDRV environment variable should fix it.

Change this line:

IF EXIST %%a:\backupusb.id SET %%USBDRV=%%a: && GOTO UniTest:

to this:

IF EXIST %%a:\backupusb.id SET USBDRV=%%a:&& GOTO UniTest:

(ie. no need for %% in front of the environment variable, and no space between the colon and the &&).

Upvotes: 1

Scott C
Scott C

Reputation: 1660

You have some seemingly random %% in there.

Change

IF EXIST %%a:\backupusb.id SET %%USBDRV=%%a: && GOTO UniTest:

to

IF EXIST %%a:\backupusb.id SET USBDRV=%%a: && GOTO UniTest

FYI You don't need any : (colons) after your goto statements, just the text part of the label. e.g. goto end or goto find

Upvotes: 1

Related Questions