Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I detect USB insertion without polling using Ruby and WMI?

I read the following article: Using Ruby & WMI to Detect a USB Drive

However, this method would require me to keep polling inside a loop. Is it possible to register and have my script be notified when USB is inserted/ejected ?

I am looking for a Windows XP solution.

like image 932
Geo Avatar asked Nov 08 '11 19:11

Geo


1 Answers

I can't help you much with Ruby, but WMI also supports monitored events. There exists an extrinsic event called Win32_DeviceChangeEvent.

Here is a simple PowerShell code to use it:

$query = "SELECT * FROM   Win32_DeviceChangeEvent WHERE EventType=2"
Register-WMIEvent -Query $query -Action { Write-Host "A device has been inserted"}

The code given into Action parameter is called each time a device is inserted. I don't know to handle such a query in Ruby.

like image 145
JPBlanc Avatar answered Oct 16 '22 07:10

JPBlanc