Link to home
Start Free TrialLog in
Avatar of sandeepsangshetty
sandeepsangshetty

asked on

Error while executing WMI query to check whther CD inserted or not

Hi I have written code to check whether Cd inserted or not in drive using WMI wuery and VB6.

But while executing the code it throwing an error in while entering into 'For each' loop i.e Runtime error  '-21456793':Automation error.

Can any one please help me to find out the solution for this.

Private Sub Command1_Click()
  Dim strComputer
  Dim objWMIService
  Dim colItems
  Dim objItem
 
  strComputer = "."
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  Set colItems = objWMIService.ExecQuery("Select * from __InstanceModificationEvent Within 1 Where TargetInstance ISA 'Win32_CDROMDrive' and TargetInstance.MediaLoaded = True and PreviousInstance.MediaLoaded = False ")
  For Each objItem In colItems
    MsgBox "Device ID: " & objItem.DeviceID
    MsgBox "Media Loaded: " & objItem.MediaLoaded
  Next
End Sub

 

Thanks in advance
ASKER CERTIFIED SOLUTION
Avatar of Psy053
Psy053
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RobSampson
Also, as for the cause of your error, when you query an InstanceModificationEvent you can't use the For Each loop the way you have.  You need to use the iteration structure as shown here:
http://blogs.technet.com/b/heyscriptingguy/archive/2007/04/20/how-can-i-write-a-script-that-increments-a-counter-each-time-a-log-file-is-updated.aspx

Regards,

Rob.
Avatar of sandeepsangshetty
sandeepsangshetty

ASKER

Hi  RobSampson,
After going through the link I modified my code as below but that doesn't worked fine.
Its throwing an error saying that " Runtime Error :438: Object doesn't support this property or method"

What changes need to make to run this.

Private Sub Command1_Click()
  Dim strComputer
  Dim objWMIService
  Dim colItems
  Dim objItem
 
  strComputer = "."
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  Set colItems = objWMIService.ExecQuery("Select * from __InstanceModificationEvent Within 1 Where TargetInstance ISA 'Win32_CDROMDrive' and TargetInstance.MediaLoaded = True and PreviousInstance.MediaLoaded = False ")
 
 
  Do
    Set objItem = colItems.NextEvent
    If colItems <> 0 Then
        MsgBox "Device ID: " & objItem.DeviceID
        MsgBox "Media Loaded: " & objItem.MediaLoaded
    End If
 Loop

End Sub

Regards,
Sandeep
Thanks for ur reply

I tried to Execute ur code but same automation error getting .
Hi, the latest code you have is fine, except you need to change this bit:
objWMIService.ExecQuery
to this
objWMIService.ExecNotificationQuery

Regards,

Rob.