Friday, December 10, 2010

Enabling and disabling USB devices with a simple Windows shortcut

I was asked recently if there is a straightforward way to enable and disable a USB device on the fly without having to unplug the device or navigate through the Windows device manager.  Sure, one could use the Windows system tray application to eject the device, but what then do you do when you want to re-enable the device?

The classic example (at least for my gaming nerd friends) is a USB headset.  On most days I'd prefer to drop the headset and lay waste in Call of Duty with the sound pumping out of my speakers...rattling the windows while I swill back Diet Coke and laugh maniacally.  Then, my wife gets home and shakes her head as she searches her memory for any vague inkling of why she found me attractive initially.  That's when the headset gets plugged back in.

This constant unplugging and plugging of the headset is not exactly difficult, but it is a bit annoying...especially when one realizes that you are being required to perform a physical action to reconfigure the computer.  It's a computer, right?  They store recipes and guide rockets.  Why the heck can't I just tell it, "use the headset now sparky, I can't afford another divorce."  Why isn't there a way to do this by just, for example, selecting a link in the Windows Start menu?

Well, there is...and I have the secret...in 25 easy steps.  Okay, it may be a tad simpler, but not much...but if you are the adventurous type and want to know how, read on.  My example will be based on creating this capability for a Logitech G35 headset since I am writing this article for folks in the Logitech forums, but the method should be applicable to any USB device...including that USB-powered "massage wand" in your desk drawer.  I am also assuming that you are running Windows 7.  If you aren't, you are missing out...and will need to adjust related steps accordingly.

Okay, here goes.

Let's start with our eye on the prize.  This is the goal:




As you can see in that picture, I have two links in my Windows Start menu to enable and disable my headset.  When I select one of these links, a script runs and makes it so.  No UAC security prompt, no reboot, no fumbling with cables.  Hey, that's why you are here...so you knew it was possible.  Well, this is how you do it...



Step 1 - Download devcon.exe ...from somewhere

Devcon is an application distributed freely by Microsoft and which allows command line-based control of, amongst other things, USB devices.

http://support.microsoft.com/kb/311272

Hey, you didn't think that I was doing this on my own, did you?  The first rule of good software development is "don't reinvent the wheel"...so I'm not, I'm stealing someone else's.

The trick is finding the correct version of this program.  For years, the 32 bit version of Devcon (which is readily available from Microsoft) was fine for most of us. Of course, many of us are now basking in the glory of 64 bit Windows 7 goodness...and the 32 bit version of Devcon will not work for that 64 bit OS.  Instead, we need the 64 bit version, which Microsoft now makes available as a component of the Windows Driver Kit (WDK)...packaged conveniently in a 700 MB ISO disk image.  Nice.  Thanks.


Okay, well this is where we separate those who will be able to follow the instructions in this article from those who were going to trip on one of the later steps regardless - go fire up Google, find whichever version of Devcon is appropriate for your OS (32 bit or 64 bit), and download it.  Sure, Microsoft is a good source, but there are...ahem...alternative mirror sites that provide direct access to the smaller 70 KB devcon.exe application.  That's all it is by the way - an application.  There is no installer.


Go ahead, go Google...I'll wait.


Back?  Great. Let's keep this simple.  Start by creating a folder called "bin" at the root level of your C drive,  creating a folder called "headset" in that "bin" folder, and placing devcon.exe in that "headset" folder.  Okay, call it what you want it and put it wherever you want, but these instruction will assume this directory structure.  The result should look something like this:





Step 2 - Determine the ID of your USB device

Open a Windows "Command Prompt" window with elevated permissions.  Okay, if that statement didn't make sense, you may just want to stop here and just come to terms with needing to plug and unplug your device physically...because I am assuming some level of nerd skill...but just this once, I'll hold your hand.

Open the start menu, place your cursor in the "Search programs and files" text box, type "Command Prompt", right-click on the matching item, and select the "Run as Administrator" option.  That taste was free.  The next one will cost you.

Actually, you don't need elevated permissions for this step, but you will need them later, so let's keep it simple.

Now use your DOS syntax knowledge to "CD" to your new "headset" directory.  i.e., cd \bin\headset ...and then execute the following command:  devcon hwids usb* > usb_device_ids.txt

The result will be a new file in your "headset" directory named usb_device_ids.txt

Okay, this is where we separate the nerds from the guys with girlfriends.  Open that file in a text editor and scan for the name of the USB device that you want to be able to enable and disable with a single-click.  Since I am focusing on a Logitech G35 headset, I am looking for a device whose name looks somewhat similar...and I found it:



That's Notepad++ by the way - a fantastic freeware text editor, but any text editor will do...even the standard Windows Notepad.

Okay, after you find your entry, locate and copy the longer of the two "Hardware ID's".  In my case, that is:

USB\VID_046D&PID_0A15&REV_0303&MI_00

By the way, why the term ID's in that file has an apostrophe is beyond me.  Someone at Microsoft needs to read Steve's Bible .

That hardware ID is the value that we will use in subsequent scripts to specify to Devcon which hardware device that we wish to control, so if you grabbed the wrong ID, life is not going to be so good for you as we move on.



Step 3 - Create scripts to disable and enable the device

Fire up your text editor again and add the following line to a new text file:  devcon enable "USB\VID_046D&PID_0A15&REV_0303&MI_00"

...substituting your device ID for mine.  Save the file in your "headset" folder, naming it enable.bat

Create a second text file named disable.bat that contains the following line:  devcon disable "USB\VID_046D&PID_0A15&REV_0303&MI_00"

...once again, substituting your ID for mine.



Excited?  Don't be.  We are far from done...but at least we can test.

Note:  If you aren't placing devcon.exe in the same directory as these scripts, your batch files will either need to "CD" to the devcon.exe location before running the above commands or you will need to modify your system PATH variable to include the location of devcon.exe.  Thanks to Oblivion1810 for noting that issue.



You now have two batch files that you can use to enable and disable your device.  Unfortunately, they will only work when you execute them from a Command Prompt window with elevated permissions.  You can't just double-click them, nor can you right-click on them and select "Run as Administrator."  Neither approach will work.  No worries...we'll solve that problem later, but given that we have a Command Prompt window with elevated permissions, we can test them.

One word of caution - if you are running software that is "using" or "controlling" your device, the scripts won't work.  For example, my Logitech G35 ships with software that runs in the system tray and is used to configure it.  If that software is running, the scripts will not work.  Well, actually they do work, but require a reboot...which is hardly convenient.  Thus, I have disabled that program.  If you have a G35, you can do so temporarily by right-clicking on that application in the system tray and selecting "Exit."  Unfortunately, it will come back after you reboot.  If you want to avoid that hassle, Google msconfig to learn how you can disable it permanently...or at least until you decide to re-enable it.

Okay, assuming that you have solved that issue, we are ready to test.  First, make sure that your headset (or other device) is connected and functioning.  Next, in the Command Prompt window that we opened earlier (with elevated permissions), enter the following:  disable

If all went as planned, your device is disabled.  Try testing it.  If it is headset, check to ensure that your computer's sound is now coming out of your speakers.  It's not?  Check the volume control...and if that isn't the problem, you may need to start shutting down applications.  Why?  If an application is using your audio drivers, the script cannot disable the sound device.  Such applications include games and, believe it or not, your browser.  Yes, your browser.  Blame Flash.  If you visited a site with Flash in your current browser session, the Flash plugin is probably still loaded in the background and will prevent disabling your sound device...at least in this manner.  Thus, if the disable device script didn't seem to work, try shutting down applications and then trying again.

If you have shut down all of your applications and disabled any device-specific system tray applications and the disable script still doesn't work, you may need to go back to the prior steps and see if you downloaded the wrong version of Devcon, copied the wrong hardware device ID, or missed some other critical step.  If, on the other hand, the script did work, fantastic.  Now test your enable.bat script and ensure that the device is enabled once again.  If so, we are ready to deal with the need to execute the scripts from an elevated permission Command Prompt window.

By the way, if you are still using Windows XP, skip directly to Step 6. Yes, good news!  No UAC = an easier (and riskier) life!



Step 4 - Create Windows Scheduler Tasks

This approach seems bizarre, but it not only works, the strategy is recommended by many sources to bypass UAC prompts for Windows shortcuts...so have a little faith.

Open the windows Task Scheduler by opening the start menu, placing your cursor in the "Search programs and files" text box, typing "Task Scheduler", and selecting the matching result.

This window will open:


Of course, the tasks in your window will depend on your system.

Next, we need to create a task for the enable function.  Don't worry, it won't be a scheduled task.  Instead,  we will create a task that only executes when we instruct it to run...and to run with (wait for it) elevated permissions.

Under the Task Scheduler's "Actions" menu, select the "Create Task..." option.  You will then see a window that looks like this:


Enter the following values into the indicated fields on the "General" tab...leaving all other fields set to their default values:

  • Name:  Enable Headset
  • Run with highest privileges:  checked

The result will look something like this:




Now switch to the "Actions" tab, click the "New..." button, and enter the following value into the indicated field...once again, leaving all other fields set to their default values.::

  •  Program/script:  C:\bin\headset\enable.bat

The result will look something like this:



Click the "OK" button and you will then be back on the "Actions" tab, which should look something like this:


Click the "OK" button to complete defining your Enable Headset task...and then rinse and repeat to create a Disable Headset...pointing the "Program/script" value to your disable.bat script.


We can now test the tasks to ensure that they work.  To do so, click on the "Task Scheduler Library" item in the Task Scheduler's left-hand navigation pane.  You should now see a list of all tasks defined on your system:


Next, click your "Enable Headset" task and select "Run" from the application's right-hand command pane.  Verify that your device is enabled...and then "Run" the "Disable Headset" task...to verify that your device is now disabled.

Note: If it doesn't seem to work reliably, you might try pausing for a brief period between invocations...because while you could slam USB enable commands at Devcon under Windows XP, it seems to be somewhat more sensitive under Windows 7...at least on my system with this specific headset.

If things worked as planned, you are much closer to those two icons in the Windows Start menu.



Step 5 - Create scripts to call the tasks

It's time to create two new batch files, which will call the tasks that you just created. Open your text editor once again and add the following line to a new text file:  schtasks /run /tn "Enable Headset"

Save the file in your "headset" folder, naming it Enable Headset.bat


Create a second batch file named Disable Headset.bat that contains the following line:  schtasks /run /tn "Disable Headset"


You should now be able to double-click on each of these files from Windows Explorer to enable and disable your headset (or other device).



Step 6 - Make it pretty

The next step is to create a custom icon for each batch file.  The easiest way is to accomplish this goal is to create a Windows shortcut to each batch file and then change the icons for those shortcuts.

To change a shortcut's icon, right-click the shortcut, select "Properties", and then click the "Change Icon..." button.  If you are not sure where to find a decent icon, it's Google time again.

You are now ready to add the two commands to your Windows Start menu, which you can do by holding down your Shift key while right-clicking on each shortcut and then selecting "Pin to Start Menu."



Yeah, the process should be easier.  This is the point at which someone posts a comment that points to a freeware utility that provides this capability.  I hate that person.

cheers,
Scuba

23 comments:

  1. It works perfectly for me when I run this through the command prompt, but i defined the tasks in scheduler exactly as you wrote, but the tasks do not achieve the desired result when running them. I don't get an error message or anything, it just says the tasks are running.

    For some reason, even after i run either of the defined tasks, they continue to run instead of going back to ready after executing them.

    ReplyDelete
  2. The task should execute in less than a second...so I agree, something went off the rails.


    Suggestions:

    1) Ensure that all of the settings are as specified above, including "Run with highest privileges"

    2) Ensure that you don't have any other software running that may be using the sound drivers. To start, test with all other applications closed, including your browser, which could have the Flash plug-in loaded, and any system tray utility that controls your sound device.


    Item 2 seems like a more likely fix for you since you stated that you are confident about the task settings...and since hanging usually indicates difficulty in changing the driver settings.

    cheers,
    Steve

    ReplyDelete
  3. Its funny, when i execute with a command prompt, it'll work even if a youtube video is playing at the time, but it still just doesn't go through when I run the task.

    And yes, I checked the priveleges, they are all legit. I even started task scheduler in admin mode to be safe

    ReplyDelete
  4. I had same issue as Raghav... I hit "print screen" real fast when running the task and found that the command prompt was running from the "System32" meaning the "devcon ..." command was not found.
    I added a line "cd \Bin\Speaker" to the enable.bat and the disable.bat files and now it works GREAT! Thanks Scuba for the awesome directions! (Note: "speaker" is because I am disabling a USB speaker on my laptop, you would most likely need "headset")
    Hope this helps...

    ReplyDelete
    Replies
    1. Excellent! Thanks much Oblivion. Good stuff! You could also place devcon in system32 or modify your env PATH variable to point to its current location...but I tend to prefer to modify the BAT as you have done. Much cleaner.

      cheers,
      Scuba

      Delete
  5. "Okay, this is where we separate the nerds from the guys with girlfriends."

    I was able to follow your directions just fine. But I think my HUSBAND is going to get awfully confused when I start calling him my "girlfriend".

    PS Thank you for the very clear and easy-to-follow directions. Even if you did assume that everyone reading them would be male.

    ReplyDelete
  6. Did anyone ever solve the problem where task scheduler sets the status to "run" and it never actually runs? I can test the batch files from the command prompt but task scheduler never works. It just hangs on "run."

    I am using windows 7 64bit and followed your directions exactly.

    ReplyDelete
  7. okay I think I got over this hump, it was DEAR_Austin's post here:
    http://social.technet.microsoft.com/Forums/en-US/winservermanager/thread/d47d116e-10b9-44f0-9a30-7406c86c2fbe/

    They still say "running" but they you know acutally do the things they're supposed to. maybe I'll fiddle around and tell them to terminate after an hour to be safe? Thanks for the guide!

    ReplyDelete
  8. Hahaha Okay! Okay now I am stuck at the next step. When I type into a command prompt with elevated privileges "schtasks /run /tn "Enable Headset"" it works. It runs that task. It doesn't by just clicking the new batch file with the exact same command inside of it.

    ReplyDelete
  9. Sorry to post so much on your helpful thing, but I have found out that the new new batch files, as written, work fine... in a command prompt with elevated permissions. Without, I get "ERROR: Access is denied"

    ReplyDelete
    Replies
    1. Hmmm. Which batch files? The batch files to run the scheduled tasks? They should not require elevated permissions to execute...assuming that you checked the box for "Run with highest privileges" when you defined each task. In fact, that's the only reason to create the scheduled tasks - so that you can run the scripts without needing to do so from an elevated command prompt.

      Delete
    2. Yes, I did click elevated privileges, and they still won't run. I found another how-to about how to use task scheduler to call command prompt, and with added parameters to call the scheduled task, and so I nestled these commands under yet another layer of scheduled tasks, and then added the word "exit" to the original deepest batch files so that they command prompt will disappear when done, and it finally works and I could continue.

      Convoluted as heck but I'm happy.

      Delete
    3. Hmmm...very odd, but glad to hear that you found a workaround.

      Delete
  10. right i have managed to download Devcon,,,
    for some strange reason the 64bit version isnt working on my 64bit OS.. the 32bit version is..

    i have followed this to the letter but getting error message
    USB\VID_046D&PID_0A15&MI_00\7&2E3B00D1&0&0000 : Enable failed
    No devices enabled.

    ReplyDelete
    Replies
    1. Unfortunately, it is hard to determine where this procedure may go off the rails for folks...and why. That will depend on the specific device that you are attempting to disable and any software that you have loaded that may be using the device while you are attempting to disable it.

      That said, getting Devcon to work from an elevated command prompt should be fairly straightforward. After you have 1) downloaded Devcon; 2) used it to determine the device ID to be controlled; and 3) opened an elevated command prompt window, you should just be able to type:

      devcon enable "USB\VID_046D&PID_0A15&REV_0303&MI_00"...substituting your ID for mine.

      If that doesn't work, there is no need to go further...at least until you solve that problem. I suggest reverifying that:

      1) The device is enabled currently,
      2) You have the correct device ID,
      3) You are in an elevated command prompt, and
      4) No software (including a system tray item) is currently using the device.


      Also, if you have a 64 bit OS, I have no idea why only the 32 bit version works. The opposite should be true.

      Delete
    2. thanks for the reply Scuba Steve..
      http://www.sevenforums.com/drivers/50932-64-bit-os-use-devcon-install-driver-issue.html

      there are people having the same issue as me.. the 32bit version running on my 64bit OS.
      i admit im not into programming but i am a computer repair tech. so i can hold my own...
      i would have replied with the same as you to my own post but im kinda stumped on a work around..

      Delete
    3. Thanks for the link. That helps.

      The individual who started that forum thread does not have the correct version of Devcon, as noted by someone in that thread. They downloaded the Itanium version of 64 bit Devcon. That version will only work on Itanium-based systems. It will not work on Intel or AMD-based systems.

      You need the AMD 64 bit version (amd64) - not Itanium (ia64). Fortunately, the same thread links to a second thread for a solution:

      http://answers.microsoft.com/en-us/windows/forum/windows_7-hardware/devcon-not-working-correctly-in-windows-7/9abcc12c-d7db-4249-aec4-fc4ff0ea6ee8

      In that thread, a poster states what I stated under step 1 - the proper 64 bit version is available from Microsoft in the Windows Driver Kit DVD ISO. Even better, a poster in that second thread explains how to get Devcon out of that ISO image without burning a DVD or mounting the ISO...using UniversalExtractor.

      I wish that I could host the proper version here, but Microsoft forbids redistribution. Interestingly enough, several posters in that second thread have placed the file on various file sharing sites. Whether or not those links are still valid is unclear...as is what you will get when you download something from one of those sites. If you have a broadband connection, I suggest just downloading the ISO and following the instructions in that second thread.

      Delete
  11. I have followed the directions but can't get this to work correctly. I have had some success using the cmd prompt to enable and disable the headphones(G35's on a Win 7 Ultimate 64-bit system) but it has been limited. Many times I'll get message when disabling that I need to restart my device. Absolutely no luck getting this to work with the Task Scheduler. Any ideas?

    ReplyDelete
  12. Dear Steve,
    Thank you for your guide it seems to have helped a lot of people with these shortcuts. I, on the other hand, have a slight problem. Though I followed your guide to the letter, I have a bit of a different situation. My headset (logitech h600) is wireless with a USB adapter for charging. I cannot seem to find a way that I can make this work for me. I want to switch from speaker function to headset function and the other way around without having to spend 5 minutes trying. Plus, my other problem is that when I change the device from the Sound in control panel, I have to restart every application I want in order to be heard from the headset. Any ideas? Thank you in advance.

    ReplyDelete
  13. Steve, thanks for these instructions. I got it working with ONE exception. If I have the headset disabled, and am listening to something, say, iTunes, I can run the enable script and the headset turns on. Cool...Perfect. But I cant just run the disable script while sound is playing to switch back to speakers...what happens is the script gets held up, I get a message that I must restart the system, and the Scheduler Task is left in the run state. I found I have to close iTunes to get it to disable like its supposed to. Ideally I would like it to flip back and forth while sound is playing (like music, or a conference call on Webex, or whatever)...its kind of limited having to shut down all my apps to go back to speakers. Do you have to close apps to switch?

    ReplyDelete
  14. I scoured the internet for exactly this and your blog post was the only one that solved this issue for me! In this day and age, that is rare.

    I did run into one problem. When I enable my device - play youtube - stop youtube - disable my device, I find that it doesnt reliably disable. I need to go and enable -> disable again before it works. A small price to pay for the convenience. (I'm running Win10 btw)

    Now I dont have to worry about my daughter ripping out out the fat USB connector sticking out the front of my PC. (Yes, that means I'm married ... and previously had a girlfriend!)

    ReplyDelete
  15. To add to my previous comment, this is what is returned from the disabled command:

    USB\VID_046D&PID_XXXXXXX : Disabled on reboot
    The 1 device(s) are ready to be disabled. To disable the devices, restart the devices or reboot the system .

    I think the browser must be holding on to the headset

    ReplyDelete