How to run a file automatically upon detection of USB | Nagarams Blog

Saturday, 15 November 2014

How to run a file automatically upon detection of USB

Rate this Post:

In the previous post "VBScript to Auto Detect the USB event...", we have tried to automatically detect the USB event using VBScript and to Echo the result.

USB Detected

      Now Let's try to modify the same VBscript to run a file automatically upon detection of USB or to trigger a specific file when ever USB is connected to computer.

Now as example I'm running a Shortcut Virus Removal batch file automatically upon detection of USB
  •  The VB-script will detect the USB event upon it's connection and will run the shortcutvirusremoval.bat file which can remove the shortcut virus from the USB.
  • You can download the shortcutvirusremoval.bat file and place the file in C:\ drive. (you can place the file any where in your PC but have to change the line in the below script with red color according to the file path you saved)
The modified script is as given below.

                ---------------------------------------------------------------------------------------------

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set wmiEvent = objWMIService.ExecNotificationQuery( _
    "Select * From __InstanceCreationEvent Within 1" & _
        " Where TargetInstance ISA 'Win32_PnPEntity' and" & _
            " TargetInstance.Description='USB Mass Storage Device'")
set shell=createobject("wscript.shell")
While True
Set usb = wmiEvent.NextEvent()
Select Case usb.Path_.Class
Case "__InstanceCreationEvent" shell.run "C:\shortcutvirusremoval.bat"
End Select      
Wend
Set wmiEvent = Nothing
Set objWMIService = Nothing
set shell=nothing


             -------------------------------------------------------------------------------------------------

  • You can copy paste the above script in to note pad and save it with .vbs extension or you can download the file here.
  • Place the .vbs  file in startup-programs folder and just run the file once by double clicking it.
  • From now onwards, USB drive will be detected by VBScript up on it's connection and will run the shortcut virus removal.bat file which can remove the Shortcut virus from the pen drive.
 You can run multiple files automatically upon detection of USB by repeating the line in green color with the proper file path.

 Having trouble doing this???

Feel free to contact.
Thank You
Please leave your Comments

No comments :

Post a Comment