Thursday, October 18, 2007

Safely Removing SATA and USB drives with a batch file

The devcon utility from Microsoft Downloads is what does it, but it's had me baffled for years. So now I've finally figured it out.

First we have to identify our removable device. The drive we're looking for is a 120GB Seagate drive in a USB enclosure . From the command line run

devcon classes



We can make a pretty good guess that our hard drive is going to fall within the class named "DiskDrive."

Now run the command

devcon listclass diskdrive



This lists all the Device Instance IDs in the DiskDrive class. At the bottom of the list are two USB Device Instance IDs. The bottom one is clearly the USB enclosure with our Seagate drive.

So here's our command:

devcon remove @usbstor\disk^&ven_st312002*
  • We need the "@" symbol at the beginning of the Device Instance ID string to let devcon know that the string is in fact a Device Instance ID.

  • We need to insert the "^" symbol preceding any occurrence of the "&" symbol; otherwise the string immediately following the "&" will be interpreted as a separate command.

  • We need to truncate the Device Instance ID string and add the "*" wildcard at the end of it rather than using the whole Device Instance ID string because we want the command to work with any of our USB enclosures containing Seagate 120GB drives that we're swapping in for backups.
Now let's run the command.



Did it work? Let's do the devcon listclass diskdrive command again.



The USB enclosure with our 120GB Seagate drive is gone.

What if we need to re-con
nect this USB drive without trucking out to the customer site? Just run devcon rescan and then run devcon listclass diskdrive to confirm.






4 comments:

Mycroft said...

Hi Frank,

Just curious, what application are you going to use this for?

Bob Muir

Frank Denman said...

1) If you've got a server backing up to a SATA or USB drive, the person swapping out drives every day can do so without having to log on to the server.

2) If you've got an external SATA drive that's not recognized by Windows as a removable drive and therefore does not trigger the appearance of the "Safely Remove Hardware" icon in the System Tray, you can run the bat file at will whenever you want to disconnect the drive.

Frank

Mycroft said...

Very cool applications. Thanks Frank!

Unknown said...

I'd love to be able to do this via batch file. I tried it on my WinXP Pro PC and get a message that reboot is required.

>devcon remove @usbstor\disk*
USBSTOR\DISK&VEN_WDC_WD16&PROD_00SB-01RFA0&REV_\DEF107D21CDB&0: Removed on reboot
Not all of 1 device(s) removed, at least one requires reboot to complete the operation.

I was hoping for a "noreboot" or "force" option but didn't see anything like that.

Am I missing something...or sometimes it works and sometimes it doesn't...