I am trying to set up a scheduled task in Windows that automatically copies the contents of a USB drive to a specific folder each time the drive is inserted. I am currently tracking event 2003 (usb drive mount) to obtain the drive’s ID, but I am unsure of how to determine the drive letter that the drive is mounted on.
Here is an example of the script that I would like to use for the task:
@xcopy /E /C /Q /H /Y %%sourcedrive%%\ %systemdrive%\usb_backups%%UUID%%%%date%%\
However, I am uncertain of how to set the variables %%sourcedrive%% and %%UUID%% in this script.
3 Answers
Introduction
Backing up important data is a crucial part of computer maintenance. USB drives are a popular choice for storing important files, but they can easily be lost or damaged. To prevent this, it’s important to create backups of USB drives. In this blog post, we’ll show you how to set up automatic backups of USB drives in Windows using a scheduled task.
Identifying the Drive Letter
Before we can set up the scheduled task, we need to identify the drive letter of the USB drive. One way to do this is to use the Event Viewer in Windows. Follow these steps:
- Press the Windows key + R to open the Run dialog box.
- Type “eventvwr.msc” and press Enter.
- In the Event Viewer window, expand “Windows Logs” and select “System”.
- Look for event ID 2003, which indicates that a USB drive has been mounted.
- Double-click the event to open its details.
- Look for the “Data” section and find the “Device ID” value. This value should be in the format of “DeviceHarddiskVolumeX”. The “X” represents the drive letter of the USB drive.
Creating the Scheduled Task
Now that we know the drive letter of the USB drive, we can create the scheduled task to automatically back up its contents. Follow these steps:
- Press the Windows key + R to open the Run dialog box.
- Type “taskschd.msc” and press Enter.
- In the Task Scheduler window, click “Create Task” in the right-hand pane.
- Give the task a name and select “Run whether user is logged on or not”.
- Under the “Triggers” tab, click “New” and select “On an event” from the dropdown menu.
- Select “Custom” under “Settings” and click “New Event Filter”.
- In the “XML” tab, paste the following code:
<QueryList> <Query Id="0" Path="System"> <Select Path="System"> *[EventData[Data[@Name='DeviceID'] and (Data='\\\Device\\\HarddiskVolumeX')]] </Select> </Query> </QueryList>
Replace the “X” in “HarddiskVolumeX” with the drive letter of the USB drive that you want to back up.
- Click “OK” to save the filter and close the XML editor.
- Under “Actions”, click “New” and select “Start a program”.
- In the “Program/script” field, enter “cmd.exe”.
- In the “Add arguments” field, enter the following code:
/c "xcopy /E /C /Q /H /Y X: %systemdrive%usb_backupsUUID-%date:/=-%"
Replace “X” with the drive letter of the USB drive and “UUID” with a unique identifier for the backup.
- Click “OK” to save the action.
- Click “OK” to save the task.
Understanding the Script
Let’s take a closer look at the script that we used in the scheduled task:
@xcopy /E /C /Q /H /Y %%sourcedrive%% %systemdrive%usb_backups%%UUID%%%%date%%
The “@xcopy” command tells Windows to use the xcopy utility to copy files. The “/E” switch copies all subdirectories, even if they’re empty. The “/C” switch continues copying even if errors occur. The “/Q” switch suppresses the display of xcopy’s messages. The “/H” switch copies hidden and system files. The “/Y” switch suppresses the confirmation prompt when overwriting files.
The “%%sourcedrive%%” variable is replaced with the drive letter of the USB drive that triggered the scheduled task. The “%systemdrive%usb_backups” folder is where the backup will be stored. The “%%UUID%%” variable is replaced with a unique identifier for the backup, such as the serial number of the USB drive. The “%%date%%” variable is replaced with the current date in the format of “MM-DD-YYYY”.
Testing the Scheduled Task
To test the scheduled task, insert the USB drive that you want to back up and wait for a few seconds. The scheduled task should trigger and create a backup in the specified folder. You can check the folder to make sure that the backup was successful.
Conclusion
Creating automatic backups of USB drives is an important step in protecting your data. By using a scheduled task in Windows, you can ensure that your USB drives are backed up regularly and without any manual intervention. Remember to test your scheduled task to make sure that it’s working properly.
To determine the drive letter that a USB drive is mounted on in Windows, you can use the wmic logicaldisk
command in a command prompt or in a batch file. This command returns a list of all logical disks on the system, along with information about each one, such as the device ID and the drive letter.
You can use the findstr
command to filter the output of wmic logicaldisk
to just the line containing the USB drive, and then use the for /f
command to parse the drive letter from that line.
Here is an example of how you can set the variable %%sourcedrive%%
to the drive letter of the USB drive in a batch file:
for /f "tokens=2 delims=:" %%a in ('wmic logicaldisk where "DeviceID='F:'" get DeviceID ^| findstr F:') do (set sourcedrive=%%a)
The script above filter where drive F, you can replace ‘F’ to filter the drive you want.
To obtain the UUID of the drive, you can use the fsutil
command.
for /f "tokens=2" %%a in ('fsutil fsinfo ntfsinfo %sourcedrive% ^| find "Serial Number"') do (set UUID=%%a)
You can then use these variables in your xcopy
command, like so:
xcopy /E /C /Q /H /Y %sourcedrive%\ %systemdrive%\usb_backups\%UUID%\%date%\
You will need to run the command above on specific event like device insertion, you can schedule a task in task scheduler and set the event id to 2003
as trigger.
Also, you may want to add some error handling in case the device is not found or some other error occurs.
It seems that USBDLM would be an ideal solution for managing drive letter assignments for USB drives on Windows. The software describes itself as a Windows service that provides control over Windows’ drive letter assignments for USB drives, and it automatically resolves conflicts between USB drives and network or subst drives. Additionally, it allows you to define new default letters for USB drives and more. It is compatible with Windows XP to Windows 10.
The HTML help page for USBDLM states that you can use it to copy files with a single click or automatically, by displaying a balloon tip on drive arrival that shows the assigned drive letter, running a command on click on the balloon tip, and executing an autorun, depending on specified criteria. The software’s settings can be stored in an INI file or in the Windows registry.
The desired drive letters or mount points and other settings for USBDLM are defined in a text file called USBDLM.INI, which is located in the same folder as the USBDLM.EXE file. However, starting version 3.3.1, it can also read the settings from the registry and the specific path is HKLM/Software/Uwe Sieber/USBDLM. If this registry key exist, the USBDLM.INI is ignored and only the log file settings are read from the INI file.
You can also define actions to be taken when the user clicks on the balloon tip. These actions are similar to the autorun events, and you can specify different actions for left, right, and middle clicks on the balloon. Here are some examples of actions you can define:
;on left click, open a simple Explorer window with the drive [OnBalloonClick] open="%windir%\explorer" %drive%
;on right click, open a photo software [OnBalloonRClick] open="C:\Program Files\FotoSoft\fotosoft.exe" %drive%
Similar to [AutoRun], you can define several events, each with their own set of criteria.
The USBDLM.INI file includes settings for global autorun events that can be triggered by the presence of specific volumes. Here are some examples of how to use these settings:
If the file DATA.TXT exists, copy it from the drive to C:\Data
[OnArrival1]
FileExists=%drive%\DATA.TXT
open="%windir%\System32\cmd.exe" /c copy
"%drive%\DATA.TXT" "C:\Data"
In this example, when a drive with the file DATA.TXT is inserted, the command prompt (cmd.exe) is opened and the copy command is executed to copy the DATA.TXT file from the drive to the C:\Data folder.
In addition to the OnArrival function, USBDLM can also execute a command-line when a drive is “prepared for safe removal” and after a drive has been removed. This can be useful for copying files on removal or displaying balloon tips.
For instance, the following sample shows how to copy the file c:\test.txt to the folder \backup on the drive before it is removed:
[OnRemovalRequest]
open="%windir%\System32\cmd.exe" /c copy "C:\test.txt" %drive%\backup
Another example shows how to copy the file c:\test.txt to the folder \backup on the drive before it is removed, but only if the file \backup\test.txt exists on the drive to remove:
[OnRemovalRequest]
FileExists=%drive%\backup\test.txt
open="%windir%\System32\cmd.exe" /c copy "C:\test.txt" %drive%\backup
The USBDLM.INI file has several variables that can be used for these actions, such as %drive% which is the drive letter assigned to the USB drive.
There’s several Variables available, like these useful looking ones:
Variable Description Sample
-------- ----------- ------
%DriveLetter% drive letter X
%Drive% drive X:
%Root% drive root X:\
%DevName% device name Corsair Flash Voyager
%Label% volume label My flash drive
%Size% volume size 16 GB
%KernelName% kernel name \Device\Harddisk3\DP(1)0-0+d
%PartitionName% Partition name \Device\Harddisk2\Partition1
%DiskSignature% disk signature MBR 9810ABEF
%GptDiskIdGuid% GPT disk ID GUID {GUID}
%PureVolumeName% pure volume name Volume{GUID}
%DateISO% Date (yyyy-mm-dd) 2016-10-31
%Time% Time (hh:mm:ss) 12:00:00