How could I detect USB insertion without polling u

2019-06-16 07:21发布

问题:

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.

回答1:

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.