Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am writing a script that uses MS KB 823732 to temporarily prevent users from plugging in new USB storage devices. This works fine, and the HKLM\...\Services\UsbStor registry key successfully blocks newly-connected devices from being accessed.

Is there a WMI event that will tell me that a drive was connected, regardless of whether it was mounted?

I tried querying for __InstanceCreationEvent but that is apparently raised only after the drive is mounted and made available, which doesn't fit my requirements.

share|improve this question

1 Answer 1

.NET version: http://dotnetslackers.com/community/blogs/basharkokash/archive/2008/02/06/usb-port-insert-remove-detection-using-wmi.aspx

With the source: dotnetslackers.com/community/blogs/basharkokash/archive/2008/03/15/USB-Detection-source-code.aspx

Relevant section:

static void AddInsetUSBHandler()
{

    WqlEventQuery q;
    ManagementScope scope = new ManagementScope("root\\CIMV2");
    scope.Options.EnablePrivileges = true;

    try
    {

        q = new WqlEventQuery();
        q.EventClassName = "__InstanceCreationEvent";
        q.WithinInterval = new TimeSpan(0, 0, 3);
        q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
        w = new ManagementEventWatcher(scope, q);
        w.EventArrived += new EventArrivedEventHandler(USBAdded);
        w.Start();

    }

    catch (Exception e)
    {

        Console.WriteLine (e.Message);
        if (w != null)
              w.Stop();

    }

}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.