VBScript to Auto Detect the USB event... | Nagarams Blog

Saturday 8 November 2014

VBScript to Auto Detect the USB event...

Rate this Post:


Hi all .. In daily life you may come across the USB insertion and removing notification messages in your PC while you connect and disconnecting the USB flash drive. Have you ever imagine, how do they occur automatically !!!

From today on wards you can generate the intended dialogue message boxes when you connect your USB and also you can perform the certain tasks like running the batch scripts, copying the files, removing the files and any other tasks you wish, upon the Auto detection of USB event in your PC.

The VBScript to detect the USB event based on WMI(Windows Management Instrumentation) notification is

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

strComputer = "." '(Any computer name or address)
Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set wmiEvent = wmi.ExecNotificationQuery("select * from __InstanceOperationEvent within 1 where TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.Description='USB Mass Storage Device'")
While True
Set usb = wmiEvent.NextEvent()
Select Case usb.Path_.Class
Case "__InstanceCreationEvent" WScript.Echo("USB device found")
Case "__InstanceDeletionEvent" WScript.Echo("USB device removed")
Case "__InstanceModificationEvent" WScript.Echo("USB device modified")
End Select
Wend
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------


In the above script the red colored instructions are the events that can be detected and the green colored instructions are the tasks (in the above, the echo task will be performed) that can be performed.

  • You can choose the Case you need, and can perform any tasks like copy,remove, running batch scripts etc. by adding the tasks. 
  • To run the script just download VBScript to auto detect the USB event.vbs file or copy the above script to notepad and save it with .vbs extention.
  • Once you run the above file, it will detect USB event until system Shutdown. But, if you want to run the file on  each start up automatically, just place the VBScript to auto detect the USB event.vbs file at start up programs.
How to place a file in Start up programs? Read this Post
    How to run a file automatically upon detection of USB event was published in next post

    Thank you for your patience reading of the post & I think it is some what useful to you. Soon we will come back here with another post with useful information.......

     Please leave your comment.

    No comments :

    Post a Comment