DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

David has posted 23 posts at DZone. View Full User Profile

Using Ruby & WMI To Detect A USB Drive

06.17.2007
| 4920 views |
  • submit to reddit
        From the <a href="http://rubyonwindows.blogspot.com">Ruby on Windows</a> blog.

How to use Windows Management Instrumentation (WMI) to determine if a "USB Mass Storage Device" is inserted.
require 'win32ole'

wmi = WIN32OLE.connect("winmgmts://")

devices = wmi.ExecQuery("Select * From Win32_USBControllerDevice")
for device in devices do
    device_name = device.Dependent.gsub('"', '').split('=')[1]
    usb_devices = wmi.ExecQuery("Select * From Win32_PnPEntity Where DeviceID = '#{device_name}'")
    for usb_device in usb_devices do
        puts usb_device.Description
        if usb_device.Description == 'USB Mass Storage Device'
            # DO SOMETHING HERE
        end
    end
end
Further details can be found <a href="http://rubyonwindows.blogspot.com/2007/06/using-ruby-wmi-to-detect-usb-drive.html">here</a>.