Is there a way to “Safely Remove Hardware” from a batch file?
Many USB and Firewire devices can be removed from your computer
simply by unplugging. Other devices aren’t as easy because the
operating system might need to complete an operation to shut the device
down safely. Windows provides an icon in the taskbar that allows you to
“Safely Remove Hardware” but if you want to automate the shutdown as
part of a more complex process you need something more.
As an example, I recently purchased a Maxtor
external hard drive and before I remove it I’d like to run a
batch file that copies a few files around. It would be nice if that
batch file could also invoke Windows “Safely Remove Hardware” when it
finishes so I can then just unplug the drive.
Now it can.
Become a Patron of Ask Leo! and go ad-free!
Microsoft provides a utility called devcon
for free download. It’s a “Command Line Uility Alternative to Device
Manager”. It can actually do many things that I won’t get into here,
but removing a plug & play device is a simple operation once you know
the unique name of the device you want to manipulate.
After you’ve downloaded devcon, run “devcon status *” in a command
window. This will generate a list of all the devices on your system. Look for the
line which describes your device. In my case for my external hard
drive the (very cryptic) line looks like this:
That full line is a bit much but any substring that remains unique
will do. I have another maxtor drive on my system but nothing
else that has the phrase “sbp2\maxtor” so I’ll use that. The command to safely
remove my external drive then becomes:
devcon remove sbp2\maxtor*
The “*” at the end is a wildcard and matches the rest of the string.
Be certain to select the right device. In my case, installing the
Maxtor drive actually installed three devices all labeled with
“maxtor onetouch” – its firewire interface, its front panel
interface, and finally the drive itself. It’s the latter that I want to
remove. Looking at the details of the “Safely Remove Hardware” dialog
will help you select the appropriate entry.
Finally, be careful. Devcon can certainly cause problems if you
delete the wrong device by mistake. A reboot or a re-run of the “add
new hardware” wizard may restore you, but that’s a risk I’d rather