WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

2004B and Newer

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

!! WMI_Scripter !!

 Keywords: wmi_scripter  new 

;********************************************************************
;*
;*  File:           WMI_scripter.wbt
;*  Created:        Jun 1st 2011
;*  Version:        8.0
;*
;*  Description:    Learning tool. Enables users to generate and run
;*                  scripts that use WMI to display properties available
;*                  through the Win32_ classes.
;*
;*  Requirements:   Requires WinBatch 2008E or newer.
;*
;*  Version I - June 11th, 2003 DRD
;*         Initial Release
;*
;*  Version II - June 14 2003  Assorted hacks MW
;*
;*  Version III - Feb 24 2003
;*         Modified for 2004B changes. Use For Each instead of ObjectCollect_ functions
;*         Modified wmi script output.
;*           Added code to check if WMI is installed.
;*           Added system menus to WIL popup windows.
;*           Made dropdown listbox 'list only' style, so user couldn't type in the edit field.
;*           Immediately update dropdown edit box with selected item.
;*
;*  Version IV - March 12 2003
;*           Changed udfMakeVar variablenames from beginning with var to prop. Fixed missing h in udfMakeVar.
;*
;*  Version V - April 4 2005
;*          Only prompt user to if more than once instance to choose from. (i.e. win32_operatingsystem)
;*
;*  Version VI - April 12 2005
;*          Only allow user to to select one instance from the instance list.
;*
;*  Version VII - Jan 26 2006
;*          Added code that will escape backslashes in WMI query strings. Code generated now sets the object variable
;*          to zero to close the handle instead of using ObjectClose.
;*
;*  Version VIII - Jun 1 2011
;*          Updated code to use 6.2 formatted dialogs. Requires WinBatch 2008E or newer.
;*          Code now sets the object variable to zero to close the handle instead of using ObjectClose.
;*
;********************************************************************

;============================================================
; InitDialogConstants
;============================================================
#DefineSubRoutine InitDialogConstants()
   ;DialogprocOptions Constants
   MSG_INIT=0                ; The one-time initialization
   MSG_TIMER=1               ; Timer event
   MSG_BUTTONPUSHED=2        ; Pushbutton or Picturebutton
   MSG_RADIOPUSHED=3         ; Radiobutton clicked
   MSG_CHECKBOX=4            ; Checkbox clicked
   MSG_EDITBOX=5             ; Editbox or Multilinebox
   MSG_FILESELECT=6          ; Filelistbox
   MSG_ITEMSELECT=7          ; Itembox
   MSG_COMBOCHANGE=8         ; Combobox/Droplistbox
   MSG_CALENDAR=9            ; Calendar date change
   MSG_SPINNER=10            ; Spinner number change
   MSG_CLOSEVIA49=11         ; Close clicked (Enabled via DialogProcOptions 1002
   MSG_FILEBOXDOUBLECLICK=12 ; Get double-click message on a FileListBox
   MSG_ITEMBOXDOUBLECLICK=13 ; Get double-click message on an ItemBox
   MSG_COMEVENT=14           ; COMCONTROL Event notification from DialogObject (NOT DialogProcOptions)
   MSG_MENUITEM=15           ; MenuItem selected
   MSG_MENUITEMINIT=16       ; MenuItem initialized
   MSG_RESIZE=17             ; Dialog resized

   DPO_DISABLESTATE=1000     ; codes -1=GetSetting 0=EnableDialog 1=DisableDialog
   DPO_CHANGEBACKGROUND=1001 ; -1=Get Current otherise bitmap or color string
   DPO_CHANGESYSMENU=1002    ; -1=Get Current 0=none 1=close 2=close/min 3=close/max 4=close/min/max
   DPO_CHANGETITLE=1003      ; Set/Get Dialog Title - (-1 to get)
   DPO_GETNAME=1004          ; Returns the name associated with a control's number.
   DPO_GETNUMBER=1005        ; Returns the number associated with a control's name.
   DPO_GETCLIENTAREA=1007    ; Returns a space delimited list of the width and height of the client area.

   ;DialogControlState Constants
   DCSTATE_SETFOCUS=1        ; Give Control Focus
   DCSTATE_QUERYSTYLE=2      ; Query control's style
   DCSTATE_ADDSTYLE=3        ; Add control style
   DCSTATE_REMOVESTYLE=4     ; Remove control style
   DCSTATE_GETFOCUS=5        ; Get control that has focus
   DCSTATE_MOVEMOUSEOVER=6   ; Move the mouse over the control

   DCSTYLE_DEFAULT=0         ; Set Default Style
   DCSTYLE_INVISIBLE=1       ; Set Control Invisible
   DCSTYLE_DISABLED=2        ; Set Control Disabled
   DCSTYLE_NOUSERDATA=4      ; Note: Setable via DialogControlState function ONLY SPINNER control only
   DCSTYLE_READONLY=8        ; Sets control to read-only (user cannot type in data) EDITBOX MULTILINEBOX SPINNER
   DCSTYLE_PASSWORD=16       ; Sets 'password mode' where only *'s are displayed EDITBOX
   DCSTYLE_DEFAULTBUTTON=32  ; Sets a button as the default button PUSHBUTTON PICTUREBUTTON
   DCSTYLE_DIGITSONLY=64     ; Set edit box to accept digits only EDITMOX MULTILINEBOX
   DCSTYLE_FLAT=128          ; Makes a 'flat' hyperlink-looking button PUSHBUTTON PICTUREBUTTON
   DCSTYLE_NOADJUST=256      ; Turns off auto-height adjustment  ITEMBOX FILELISTBOX
   DCSTYLE_TEXTCENTER=512    ; Center text in control VARYTEXT STATICTEXT
   DCSTYLE_TEXTRIGHT=1024    ; Flush-Right text in control VARYTEXT STATICTEXT
   DCSTYLE_NOSELCURLEFT=2048 ; No selection, cursor left EDITBOX MULTILINEBOX
   DCSTYLE_NOSELCURRIGHT=4096; No selection, cursor right EDITBOX MULTILINEBOX
   DCSTYLE_SHIELD=8192       ; Display Security Shield icon on button (Vista only) PUSHBUTTON PICTUREBUTTON
   DCSTYLE_MENUCHECK=32768   ; Adds a check mark to the left of a menu item MENUITEM
   DCSTYLE_MENURADIO=65536   ; Adds a radio button like dot graphic to the left of a menu item MENUITEM
   DCSTYLE_MENUSEP=131072    ; Separator bar graphic MENUITEM
   DCSTYLE_MENUBREAK=262144  ; column break MENUBAR

   ;DialogControlSet / DialogControlGet Constants
   DC_CHECKBOX=1             ; CHECKBOX
   DC_RADIOBUTTON=2          ; RADIOBUTTON
   DC_EDITBOX=3              ; EDITBOX MULTILINEBOX
   DC_TITLE=4                ; PICTURE RADIOBUTTON CHECKBOX PICTUREBUTTON VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON MENUITEM
   DC_ITEMBOXCONTENTS=5      ; ITEMBOX FILELISTBOX DROPLISTBOX
   DC_ITEMBOXSELECT=6        ; ITEMBOX FILELISTBOX DROPLISTBOX
   DC_CALENDAR=7             ; CALENDAR
   DC_SPINNER=8              ; SPINNER
   DC_MULTITABSTOPS=9        ; MULTILINEBOX
   DC_ITEMSCROLLPOS=10       ; ITEMBOX FILELISTBOX
   DC_BACKGROUNDCOLOR=11     ; RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX FILELISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX
   DC_PICTUREBITMAP=12       ; PICTURE PICTUREBUTTON
   DC_TEXTCOLOR=13           ; RADIOBUTTON CHECKBOX VARYTEXT STATICTEXT GROUPBOX PUSHBUTTON ITEMBOX FIELLISTBOX DROPLISTBOX SPINNER EDITBOX MULTILINEBOX
   DC_ITEMBOXADD=14          ; ITEMBOX FILELISTBOX DROPLISTBOX
   DC_ITEMBOXREMOVE=15       ; ITEMBOX FILELISTBOX DROPLISTBOX
   DC_RADIOVALUE=16          ; RADIOBUTTON
   DC_POSITION=17            ; ALL CONTROLS (Except MENUBAR and MENUITEM)
   DC_MENUNAMES=18           ; ALL CONTROLS
   DC_HANDLE=19              ; ALL CONTROLS (Except MENUBAR and MENUITEM)


   ;DialogObject constants
   DLGOBJECT_ADDEVENT=1      ; Call dialog callback when the specified event occurs
   DLGOBJECT_STOPEVENT=2     ; Stop calling dialog callback when an event previously requested with
   DLGOBJECT_GETOBJECT=3     ; Return an object references to the specified control
   DLGOBJECT_GETPICTURE=4    ; Create and return an object reference to a picture object

   ;Return code constants
   RET_DO_CANCEL=0           ; Cancels dialog
   RET_DO_DEFAULT= -1        ; Continue with default processing for control
   RET_DO_NOT_EXIT= -2       ; Do not exit the dialog
   Return
#EndSubRoutine

InitDialogConstants()                                       ; Initialize Dialog Constants (need only be done once usually)

;============================================================
;udfMakeVar
;============================================================
#DefineFunction udfMakeVar(p)
   v=StrClean(StrCat("prop",p),"abcdefghijklmnopqrstuvwxyz_0123456789","",@FALSE,2)
   If StrLen(v)>30 Then v=StrSub(v,1,30)
   Return(v)
#EndFunction


;============================================================
;ConnectDialogCallbackProc
;============================================================

#DefineSubRoutine ConnectDialogCallbackProc(ConnectDialog_Handle,ConnectDialog_Message,ConnectDialog_Name,ConnectDialog_EventInfo,ConnectDialog_ChangeInfo)
   ON_EQUAL = @TRUE                                         ; Initialize variable ON_EQUAL
   Switch          ConnectDialog_Message                          ; Switch based on Dialog Message type
      Case MSG_INIT                                         ; Standard Initialization message
         DialogProcOptions(ConnectDialog_Handle,MSG_BUTTONPUSHED,@TRUE)
         Return(RET_DO_DEFAULT)

     Case MSG_BUTTONPUSHED
         If ConnectDialog_Name == "PushButton_Connect"               ; Connect
            strComputer = DialogControlGet(ConnectDialog_Handle,"Editbox_1",3)
            userid = DialogControlGet(ConnectDialog_Handle,"Editbox_3",3)
            pswd = DialogControlGet(ConnectDialog_Handle,"Editbox_4",3)
            ;*********************************************
            ;* WHILE LOADING...
            ;*
            ;* As the application loads, we update the
            ;* window to act as a crude progress dialog
            ;* while we wait for the enumeration of the WMI
            ;* classes to complete.
            ;*
            ;*********************************************
            ;Update multiline with progress and red text
            txt = StrCat("Connecting to ",strComputer,". Please Wait ")
            DialogControlSet(WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)

            ;****************************************************************************
            ;* enumerate the WMI classes in the cimv2 namespace, filling up list
            ;* with the names of the classes that begin with Win32_ and are not association
            ;* classes. we'll use the class names stored in the list to populate a
            ;* DROPLISTBOX.
            ;*****************************************************************************

            If strComputer =="[LOCAL]" || strComputer =="" Then strComputer = "."

            ErrorMode(@OFF)
            objLocator = ObjectCreate("WbemScripting.SWbemLocator")
            ErrorMode(@CANCEL)
            If objLocator==0   ;Check WMI Installed
            str = "The WMI operating system core components are not installed. They are supported on Windows NT 4.0 with Service Pack 4 or later, including Windows 2000/XP/2003, and on Windows 95 OSR2 and Windows 98."
            str = StrCat(str, @CRLF, @CRLF, "For Win95, 98, and NT 4.0, you can download the Windows Management Instrumentation (WMI) CORE 1.5 from Microsoft")
            Message("WMI Not Installed", str)
            Exit
            EndIf

            ErrorMode(@OFF)
            objService = objLocator.ConnectServer(strComputer,"root/cimv2", userid, pswd)
            ErrorMode(@CANCEL)
            If objService==0   ;Check connection
            err = LastError()
            If err == 1261
                msg = StrCat("Unable to connect to ",strComputer, ". Please try again.")
                ;Read and display error in wwwbatch.ini
                If FileExist(StrCat(DirWindows(0),"wwwbatch.ini"))
                   batcherr = IniReadPvt("OLE Exception","SWbemLocator","NONE",StrCat(DirWindows(0),"wwwbatch.ini"))
                   Message("WMI Connect Error",batcherr)
                EndIf
                ;Update varytext progess on main dialog
                DialogControlSet(WBOMATIC_Handle, "VaryText_1", 4, msg)
                Return(-2)
            Else
               Message(StrCat("Error  ",err),"Unhandled Error")
            EndIf
            EndIf

            objSecurity = objService.Security_
            objSecurity.ImpersonationLevel = 3
            colClasses = objService.SubclassesOf()

            ;Update multiline with progress and red text
            txt = StrCat("Loading WMI Classes. Please Wait ")
            DialogControlSet(WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)
            iCounter = 0
            datalist = ""
            txt = StrCat(@CRLF,@CRLF,"Retrieving Instances ",@CRLF,@CRLF)
            ForEach objClass In colClasses
            ;Check if Object is EMPTY
            type = ObjectTypeGet(objClass)
             If type=="EMPTY" Then Break
            ;notify user that its querying instances
            iCounter = iCounter + 1
            If iCounter mod 50 == 0
               txt = DialogControlGet( WBOMATIC_Handle, "VaryText_1", DC_TITLE)
               txt = StrCat(txt,"|")
               DialogControlSet( WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)
            EndIf

            bIsQualifier = @FALSE
            objPath = objClass.Path_
            ClassName = objPath.Class
            If StrUpper(StrSub(ClassName,1,5)) == "WIN32"
              colQualifiers = objClass.Qualifiers_
              ForEach objQualifier In colQualifiers
                 ;Check if Object is EMPTY
                 type = ObjectTypeGet(objQualifier)
                  If type=="EMPTY" Then Break
                 If StrUpper(StrTrim(objQualifier.Name)) == "ASSOCIATION"
                    bIsQualifier = @TRUE
                 EndIf
                 objQualifier = 0
              Next

              ;* the class name starts with win32_ and is not an association
              ;* class - so append it to the list
               If bIsQualifier == @FALSE
                   datalist = StrCat(datalist, @TAB, objPath.Class)
               EndIf
               colQualifiers = 0
            EndIf

            objPath = 0
            objClass = 0
            Next
            colClasses = 0

            datalist = StrTrim(datalist)
            datalist = ItemSort(datalist,@TAB)

            ;* populate the droplistbox
            DialogControlState(WBOMATIC_Handle,"DropListbox_1",DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE)  ;  Set the visible bit on dropdown
            DialogControlSet(WBOMATIC_Handle, "DropListbox_1", DC_ITEMBOXCONTENTS, datalist )
            DialogControlSet(WBOMATIC_Handle, "DropListbox_1", DC_ITEMBOXSELECT, "*** Select a WMI class from this dropdown list ***")

            ;* enable the run and save buttons
            DialogControlState(WBOMATIC_Handle,"PushButton_Run",DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE)  ;  Set the visible bit on RUN button
            DialogControlState(WBOMATIC_Handle,"PushButton_Save",DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE)  ;  Set the visible bit on SAVE button

            ;Update Varytext with progress
            If strComputer == "."
             strComputer = ItemExtract(1,WinSysInfo(),@TAB)
            EndIf
            txt = StrCat("Connected to ",strComputer)

            DialogControlSet(WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)
            ;Update MultiLineBox to blank
            DialogControlSet(WBOMATIC_Handle, "MultiLineBox_1", DC_EDITBOX, "")
         EndIf
         Return(RET_DO_DEFAULT)
   EndSwitch                                                ;          ConnectDialog_Message
   Return(RET_DO_DEFAULT)
#EndSubRoutine                                              ; End of Dialog Callback          ConnectDialogCallbackProc


;============================================================
;WBOMATICCallbackProc
;============================================================
InitDialogConstants()                                       ; Initialize Dialog Constants (need only be done once usually)

#DefineSubRoutine WBOMATICCallbackProc(WBOMATIC_Handle,WBOMATIC_Message,WBOMATIC_Name,WBOMATIC_EventInfo,WBOMATIC_ChangeInfo)
   ON_EQUAL = @TRUE                                         ; Initialize variable ON_EQUAL
   IntControl(73,1,0,0,0) ;Error Handling
   IntControl(72,1,0,0,0) ;Cancel Handling
   strTmpName = StrCat(FilePath(IntControl(1004,0,0,0,0)),"temp_script.wbt")
   strProg = StrCat(DirHome(),"winbatch.exe")

   Switch WBOMATIC_Message                                  ; Switch based on Dialog Message type
      Case MSG_INIT                                         ; Standard Initialization message
         ;Select events to monitor
         DialogProcOptions(WBOMATIC_Handle,MSG_TIMER,1)
         DialogProcOptions(WBOMATIC_Handle,MSG_BUTTONPUSHED,@TRUE)
         ;DialogProcOptions(WBOMATIC_Handle,MSG_EDITBOX,@TRUE)
         DialogProcOptions(WBOMATIC_Handle,MSG_COMBOCHANGE,@TRUE)
         ;* disable the dropdown and run and save buttons because
         ;* they are not yet meaningful.
         ; Set the invisible bit on dropbox
         DialogControlState(WBOMATIC_Handle,"DropListBox_1",DCSTATE_ADDSTYLE,DCSTYLE_INVISIBLE)
         ; Set the invisible bit on editbox
         DialogControlState(WBOMATIC_Handle,"MultiLineBox_1",DCSTATE_ADDSTYLE,DCSTYLE_INVISIBLE)
         ; Set the invisible bit on RUN button
         DialogControlState(WBOMATIC_Handle,"PushButton_Run",DCSTATE_ADDSTYLE,DCSTYLE_INVISIBLE)
         ; Set the invisible bit on SAVE button
         DialogControlState(WBOMATIC_Handle,"PushButton_Save",DCSTATE_ADDSTYLE,DCSTYLE_INVISIBLE)
         Return(RET_DO_DEFAULT)

      Case MSG_TIMER
            DialogProcOptions(WBOMATIC_Handle,MSG_TIMER,@FALSE);disable timer callback

            ;****************************************************************************
            ;* Prompt user to choose namespace, computername, userid password.
            ;*
            ;*
            ;*
            ;*****************************************************************************
            strComputer = "[LOCAL]"
            ConnectDialogFormat=`WWWDLGED,6.2`

            ConnectDialogCaption=`WMI Connection`
            ConnectDialogX=9999
            ConnectDialogY=9999
            ConnectDialogWidth=248
            ConnectDialogHeight=112
            ConnectDialogNumControls=011
            ConnectDialogProcedure=`ConnectDialogCallbackProc`
            ConnectDialogFont=`DEFAULT`
            ConnectDialogTextColor=`DEFAULT`
            ConnectDialogBackground=`DEFAULT,DEFAULT`
            ConnectDialogConfig=0

            ConnectDialog001=`091,095,032,010,PUSHBUTTON,"PushButton_Connect",DEFAULT,"Connect",1,1,32,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog002=`007,023,232,066,GROUPBOX,"GroupBox_Credentials",DEFAULT,"Credentials",DEFAULT,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog003=`007,007,052,010,STATICTEXT,"StaticText_1",DEFAULT,"Host name:",DEFAULT,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog004=`041,007,192,010,EDITBOX,"EditBox_1",strComputer,DEFAULT,DEFAULT,5,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog005=`013,039,024,010,STATICTEXT,"StaticText_Domain:",DEFAULT,"Domain:",DEFAULT,6,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog006=`013,055,024,010,STATICTEXT,"StaticText_3",DEFAULT,"User Id:",DEFAULT,7,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog007=`013,073,024,010,STATICTEXT,"StaticText_Password",DEFAULT,"Password",DEFAULT,8,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog008=`043,039,192,010,EDITBOX,"EditBox_2",domain,DEFAULT,DEFAULT,9,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog009=`043,055,192,010,EDITBOX,"EditBox_3",userid,DEFAULT,DEFAULT,10,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog010=`043,073,192,010,EDITBOX,"EditBox_4",pswd,DEFAULT,DEFAULT,11,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            ConnectDialog011=`009,019,232,010,STATICTEXT,"StaticText_5",DEFAULT,"Note: Push 'Connect' button for local machine",DEFAULT,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`

            ButtonPushed=Dialog("ConnectDialog")
            If ButtonPushed == 0 Then Exit
            Return(RET_DO_DEFAULT)

     Case MSG_BUTTONPUSHED
        If WBOMATIC_Name == "PushButton_Run"               ; Run
            ;****************************************************************************
            ;* when the user presses the Run button, we use the Run
            ;* to run the code
            ;****************************************************************************

            ;Grab text from MultilineEditbox
            scripttext = DialogControlGet(WBOMATIC_Handle, "MultiLineBox_1", DC_EDITBOX)

            filehandle = FileOpen(strTmpName,"Write")
            FileWrite(filehandle,scripttext)
            FileClose(filehandle)

            Run(strProg,StrCat('"',strTmpName,'"'))
            Return(RET_DO_NOT_EXIT)

        ElseIf WBOMATIC_Name == "PushButton_Quit"          ; Quit
            Return(RET_DO_CANCEL)

        ElseIf WBOMATIC_Name == "PushButton_Save"          ; Save
            ;****************************************************************************
            ;* when the user presses the Save button, we present them with a prompt
            ;* and force them to give us the full path to where they'd like to the save
            ;* the script that is currently in the multilinebox.
            ;****************************************************************************
            types="All Files|*.*|WIL Files|*.wbt;*.mnu|Text Files|*.txt|"
            defsavedir=FilePath(IntControl(1004,0,0,0,0))
            ;get current class from drop list box for file name
            saveclass= DialogControlGet(WBOMATIC_Handle,  "DropListbox_1", DC_ITEMBOXSELECT)
            savename= StrCat(saveclass,".wbt")
            strSaveFileName=AskFilename("Please select where you want to save your script.", defsavedir, types, savename, 0)
            If strSaveFileName == ""
               Return(0)
            EndIf

            handle = FileOpen(strSaveFileName,"WRITE")
            scripttext = DialogControlGet(WBOMATIC_Handle, "MultiLinebox_1", DC_EDITBOX)

            FileWrite(handle, scripttext)
            FileClose(handle)
            Return(RET_DO_NOT_EXIT)
        EndIf                                              ; WBOMATIC_Name
        Return(RET_DO_DEFAULT)

;     case MSG_EDITBOX                                      ; ID "MultiLineBox_1"  text Multiline edit 1
;        return(RET_DO_DEFAULT)

     Case MSG_COMBOCHANGE                                  ; ID "DropListBox_1"  win32classes
         ;****************************************************************************
         ;* when the user selects a class from the pulldown it queries WMI
         ;* to determine the properties of the class the user selected and
         ;* uses the information to construct sample code which it puts
         ;* in the main window's multiline box.
         ;****************************************************************************
         selected = DialogControlGet(WBOMATIC_Handle, "DropListbox_1", DC_ITEMBOXSELECT)  ;get selected droplistbox item
         If StrSub(selected,1,3) == "***" Then Return (-1)

         ;Update dropdown edit box with selected item
         DialogControlSet(WBOMATIC_Handle,  "DropListbox_1", DC_ITEMBOXSELECT, selected)

         DialogControlState(WBOMATIC_Handle, "DropListbox_1",DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE)  ;  Set the visible bit on dropdown
         classlist = DialogControlGet(WBOMATIC_Handle,  "DropListbox_1", DC_ITEMBOXCONTENTS)  ;get all items in the droplistbox

         ;Force dropdown to come back up
         ;DialogControlSet(WBOMATIC_Handle, 003, 5, classlist)
         ;DialogControlSet(WBOMATIC_Handle, 003, 6, selected)
         ;* Update VaryText box
         DialogControlSet(WBOMATIC_Handle, "VaryText_1", DC_TITLE, "Retrieving data  ")
         ;* Update Multiline box
         DialogControlSet(WBOMATIC_Handle, "MultiLinebox_1", DC_EDITBOX, "")

         ;Causes this call to block until the query is complete.
         wbemFlagReturnWhenComplete = 0
         ;Causes the call to return immediately.
         wbemFlagReturnImmediately = 16
         ;Causes a forward-only enumerator to be returned. Forward-only enumerators are generally
         ;much faster and use less memory than conventional enumerators, but they do not allow
         ;calls to SWbemObject.Clone_.
         wbemFlagForwardOnly = 32
         objObjectSet  = objService.ExecQuery(StrCat("SELECT * FROM ", selected))
         ;objObjectSet  = objService.ExecQuery(StrCat("SELECT * FROM ", selected)," WQL, ", wbemFlagReturnImmediately + wbemFlagForwardOnly)
         ;objObjectSet  = objService.ExecQuery(StrCat("SELECT * FROM ", selected),, wbemFlagForwardOnly)

         ;Get a list of instances to prompt user with if more than once instance
         instancelist = ""
         ObjectSetCount = objObjectSet.Count
         If ObjectSetCount > 1   ; VERSION V CHANGE
            iCounter = 0
            ForEach objObject In objObjectSet
              ;Check if Object is EMPTY
              type = ObjectTypeGet(objObject)
              If type=="EMPTY" Then Break
              iCounter = iCounter + 1
              If iCounter mod 100 == 0
                  txt = DialogControlGet( WBOMATIC_Handle, "VaryText_1", DC_TITLE)
                  txt = StrCat(txt,"|")
                  DialogControlSet( WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)
              EndIf

              objPath = objObject.Path_
              class = objPath.Class
              colKeys = objPath.Keys
              instancelist = StrCat(instancelist,@TAB,class)
              ;Grab key name
              ForEach objKey In colKeys
                 ;Check if Object is EMPTY
                 type = ObjectTypeGet(objKey)
                  If type=="EMPTY" Then Break
                 keyname = objKey.Name
                 keyvalue = objKey.Value
                 instancelist = StrCat(instancelist,"          ",keyname," = '",keyvalue,"'"); 10 spaces
              Next
              colKeys = 0
              objPath= 0
              objObject= 0
            Next
            ;Trim Leading pipe
            instancelist = StrTrim(instancelist)
            ;* Update multiline box
            DialogControlSet(WBOMATIC_Handle, "MultiLineBox_1", DC_EDITBOX, "")
         EndIf


         ;Set Varytext process control
         txt = "Please choose a WMI Win32 class from the drop down list box."
         DialogControlSet(WBOMATIC_Handle, "VaryText_1", DC_TITLE, txt)

         ;Create copies of list, one for display and one original
         listdisplay = instancelist

         ;Prompt user to select an instance
         If instancelist != ""
            IntControl (33, 0, 0, 0, 0)
            InstanceFormat=`WWWDLGED,6.2`

            InstanceCaption=`Browse for Instance`
            InstanceX=9999
            InstanceY=9999
            InstanceWidth=352
            InstanceHeight=256
            InstanceNumControls=004
            InstanceProcedure=`DEFAULT`
            InstanceFont=`DEFAULT`
            InstanceTextColor=`DEFAULT`
            InstanceBackground=`DEFAULT,DEFAULT`
            InstanceConfig=0

            Instance001=`249,237,032,010,PUSHBUTTON,"PushButton_OK",DEFAULT,"OK",1,1,32,DEFAULT,DEFAULT,DEFAULT`
            Instance002=`295,237,032,010,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"Cancel",0,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            Instance003=`011,029,330,200,ITEMBOX,"ItemBox_1",listdisplay,DEFAULT,DEFAULT,3,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
            Instance004=`011,019,316,008,STATICTEXT,"StaticText_1",DEFAULT,"Select one object, then click OK.",DEFAULT,4,DEFAULT,DEFAULT,DEFAULT,DEFAULT`

            ButtonPushed=Dialog("Instance")

            IntControl (33, 1, 0, 0, 0)

            instance = listdisplay
            If instance==""
               Message("NOTICE","You must choose an instance")
               Return(-1)
            EndIf

            ;Remove first item in list because its the classname
            instance = StrReplace(instance,"          ",@TAB)
            instance = ItemRemove(1,instance,@TAB)
            instance = StrReplace(instance,@TAB," AND ")
            query = StrCat("SELECT * FROM ", selected," WHERE ",instance) ;," WQL ", wbemFlagReturnImmediately + wbemFlagForwardOnly)
            ;Handle backslashes in query string by using double backslashes
            query = StrReplace(query,"\","\\")
         Else
            query = StrCat("SELECT * FROM ", selected);;," WQL ", wbemFlagReturnImmediately + wbemFlagForwardOnly))
            ;Handle backslashes in query string by using double backslashes
            query = StrReplace(query,"\","\\")
         EndIf

         If strComputer =="[LOCAL]" ||strComputer =="" Then strComputer = "."
         colInstances = objService.ExecQuery(query)
         ;colInstances  = objService.ExecQuery(query,,wbemFlagForwardOnly,)
         strCode = StrCat('; connect to WMI', @CRLF)
         strCode = StrCat('objLocator = ObjectCreate("WbemScripting.SWbemLocator")', @CRLF)
         strCode = StrCat(strCode , 'objService = objLocator.ConnectServer("',strComputer,'","root/cimv2","',userid,'","',pswd,'")' , @CRLF)
         strCode = StrCat(strCode , 'objSecurity = objService.Security_' , @CRLF)
         strCode = StrCat(strCode , 'objSecurity.ImpersonationLevel = 3' , @CRLF)
         strCode = StrCat(strCode , 'class =  "', selected  , '"' , @CRLF)
         strCode = StrCat(strCode , '; query instances', @CRLF)
         If instancelist != ""
             ;Handle backslashes in query string by using double backslashes
             selected = StrReplace(selected,"\","\\")
             instance = StrReplace(instance,"\","\\")
             strCode = StrCat(strCode , `query = "SELECT * FROM `,selected,` WHERE `,instance,`"` , @CRLF)
         Else
            ;Handle backslashes in query string by using double backslashes
            selected = StrReplace(selected,"\","\\")
            strCode = StrCat(strCode , `query = "SELECT * FROM `, selected,`"`, @CRLF)
         EndIf
         strCode = StrCat(strCode , 'colInstances = objService.ExecQuery(query)',@CRLF)
         strCode = StrCat(strCode , '' , @CRLF)

         proplist=""
         strCode = StrCat(strCode , '; loop once for each instance', @CRLF)
         strCode = StrCat(strCode , 'ForEach objInstance in colInstances' , @CRLF)
         strCode = StrCat(strCode , '  ;Check if Object is EMPTY', @CRLF)
         strCode = StrCat(strCode , '  type = ObjectTypeGet(objInstance)', @CRLF)
         strCode = StrCat(strCode , '  if type=="EMPTY" then break', @CRLF)
         strCode = StrCat(strCode ,'   ; obtain properties', @CRLF)
         displaylist =""

        ForEach objInstance In colInstances
            ;Check if Object is EMPTY
            type = ObjectTypeGet(objInstance)
            If type=="EMPTY" Then Break
            colProperties = objInstance.Properties_
            ForEach objProperty In colProperties
               ;Check if Object is EMPTY
               type = ObjectTypeGet(objProperty)
               If type=="EMPTY" Then Break
               propname = objProperty.name
               strCode = StrCat(strCode , '   ',udfMakeVar(propname),' = ','objInstance.',propname, @CRLF)
               proplist = StrCat(proplist,",",propname)
               objProperty = 0
            Next
            colProperties = 0
            objInstance = 0
         Next
         colInstances = 0
         ;remove leading comma
         proplist = StrSub(proplist,2,-1)
         strCode = StrCat(strCode , 'Next' , @CRLF)
         strCode = StrCat(strCode , '' , @CRLF)
         strCode = StrCat(strCode , '; close object handles' , @CRLF)
         strCode = StrCat(strCode , 'colInstances = 0' , @CRLF)
         strCode = StrCat(strCode , 'objSecurity = 0' , @CRLF)
         strCode = StrCat(strCode , 'objService = 0' , @CRLF)
         strCode = StrCat(strCode , 'objLocator = 0' , @CRLF)
         strCode = StrCat(strCode , '' , @CRLF)
         strCode = StrCat(strCode , '' , @CRLF)
         strCode = StrCat(strCode , ';*************************************' , @CRLF)
         strCode = StrCat(strCode , ';*     Display results' , @CRLF)
         strCode = StrCat(strCode , ';*************************************' , @CRLF)
         strCode = StrCat(strCode , '#DefineSubroutine udfFormat4Display(vname)', @CRLF)
         strCode = StrCat(strCode , '   value = %%vname%%' , @CRLF)
         strCode = StrCat(strCode , '   ver = version()' , @CRLF)
         strCode = StrCat(strCode , '   yyy = ObjectTypeGet(value)', @CRLF)
         strCode = StrCat(strCode , '   if StrIndex(yyy,"ARRAY",1,@Fwdscan) !=0 ', @CRLF)
         strCode = StrCat(strCode , '     ;if array then create pipe delimited list', @CRLF)
         strCode = StrCat(strCode , '     arraylist=""', @CRLF)
         strCode = StrCat(strCode , '     cnt = ArrInfo(value,1)-1', @CRLF)
         strCode = StrCat(strCode , '     if cnt < 30 ', @CRLF)
         strCode = StrCat(strCode , '       for item = 0 To cnt', @CRLF)
         strCode = StrCat(strCode , '         arraylist = StrCat(arraylist,"|",value[item])', @CRLF)
         strCode = StrCat(strCode , '       next', @CRLF)
         strCode = StrCat(strCode , '       ;remove leading pipe', @CRLF)
         strCode = StrCat(strCode , '       value=StrSub(arraylist,2,-1)', @CRLF)
         strCode = StrCat(strCode , '     else', @CRLF)
         strCode = StrCat(strCode , '         value = "***LARGE ARRAY***"', @CRLF)
         strCode = StrCat(strCode , '     endif', @CRLF)
         strCode = StrCat(strCode , '   endif', @CRLF)
         strCode = StrCat(strCode , '   return(value)', @CRLF)
         strCode = StrCat(strCode , '#EndSubroutine', @CRLF)
         strCode = StrCat(strCode , @CRLF,@CRLF,@CRLF)
         strCode = StrCat(strCode , '; build display list',@CRLF)
         strCode = StrCat(strCode , 'displaylist = ""',@CRLF)
         propcount=ItemCount(proplist,",")

         ;get longest proper name size
         propsizemax=3
         For propitem=1 To propcount
             propname=ItemExtract(propitem,proplist,",")
             If StrLen(propname)>propsizemax Then propsizemax=StrLen(propname)
         Next


         For propitem=1 To propcount
            propname=ItemExtract(propitem,proplist,",")
            varname=UDFMakeVar(propname)
            propfill=StrFill(" ",propsizemax-StrLen(propname))
              strCode = StrCat(strCode , 'displaylist=strcat(displaylist,@LF, "',propname,propfill,' = ", UDFFormat4Display("',varname,'"))',@CRLF)
         Next

         strCode = StrCat(strCode , 'displaylist = StrSub(displaylist,2,-1)' ,@CRLF)
         strCode = StrCat(strCode , '; use fixed pitch font' ,@CRLF)
         strCode = StrCat(strCode , 'IntControl(28,1,0,0,0)' , @CRLF)
         strCode = StrCat(strCode , '; define coordinates for AskItemList' ,@CRLF)
         strCode = StrCat(strCode , 'IntControl(63,200,200,800,800)' , @CRLF)
         strCode = StrCat(strCode , 'AskItemList(class,displaylist,@LF,@unsorted,@single)' , @CRLF)

         strCode = StrCat(strCode , 'Exit' , @CRLF)

         DialogControlState(WBOMATIC_Handle,"MultiLinebox_1",DCSTATE_REMOVESTYLE,DCSTYLE_INVISIBLE)  ;  Set the invisible bit on editbox
         DialogControlSet(WBOMATIC_Handle, "MultiLinebox_1",  DC_EDITBOX, strCode);update multiline box with WMI code
         DialogControlSet(WBOMATIC_Handle, "MultiLinebox_1",  DC_ITEMSCROLLPOS, 1);show code starting from top  ;MHW

         ;* once the code is successfully composed and put into the multiline box, ensure
         ;* that the run and save buttons are enabled
         ;run_button.disabled = False
         ;save_button.disabled = False

        ;  Do default processing
        Return(RET_DO_DEFAULT)

   EndSwitch                                                ; WBOMATIC_Message
   Return(RET_DO_DEFAULT)

   :WBERRORHANDLER
   error=LastError()
   msg = ""
   msg = StrCat(msg,"LastError Value is ",error,@CRLF)
   msg = StrCat(msg,"LastError String is ",IntControl(34,Error,0,0,0),@CRLF)
   msg = StrCat(msg,"wberrorhandlerline ",wberrorhandlerline,@CRLF)
   msg = StrCat(msg,"wberrorhandleroffset ",wberrorhandleroffset,@CRLF)
   msg = StrCat(msg,"wberrorhandlerassignment ",wberrorhandlerassignment,@CRLF)
   Message("Error",msg)


   :CANCEL
   Return(-2)

#EndSubRoutine                                              ; End of Dialog Callback WBOMATICCallbackProc


; Adds system menus to WIL popup windows.
IntControl(49,1,0,0,0)

;Check WinBatch 2008E or newer
ver = Version()
If StrLen(ver) > 3
   If !(ver >= "2008E")
      Message("WMI Scripter Error","Need WinBatch 2008E or newer to run this script")
      Exit
   EndIf
Else
   Message("WMI Scripter Error","Need WinBatch 2008E or newer to run this script")
   Exit
EndIf

title = "WMI_Scripter - WMI Code Generator "
WinTitle("",title)


WBOMATICFormat=`WWWDLGED,6.2`

WBOMATICCaption= "%title%"
WBOMATICX=9999
WBOMATICY=9999
WBOMATICWidth=352
WBOMATICHeight=256
WBOMATICNumControls=006
WBOMATICProcedure=`WBOMATICCallbackProc`
WBOMATICFont=`DEFAULT`
WBOMATICTextColor=`DEFAULT`
WBOMATICBackground=`DEFAULT,DEFAULT`
WBOMATICConfig=0

WBOMATIC001=`095,237,032,010,PUSHBUTTON,"PushButton_Run",DEFAULT,"Run",1,1,32,DEFAULT,DEFAULT,DEFAULT`
WBOMATIC002=`143,237,032,010,PUSHBUTTON,"PushButton_Quit",DEFAULT,"Quit",0,2,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
WBOMATIC003=`009,017,330,212,DROPLISTBOX,"DropListBox_1",win32classes,DEFAULT,DEFAULT,3,4,"Microsoft Sans Serif|6963|40|34","0|0|0",DEFAULT`
WBOMATIC004=`009,031,330,198,MULTILINEBOX,"MultiLineBox_1",text,"Multiline edit 1",DEFAULT,8,DEFAULT,"Courier New|6963|40|49","0|0|0",DEFAULT`
WBOMATIC005=`191,237,032,010,PUSHBUTTON,"PushButton_Save",DEFAULT,"Save",2,5,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
WBOMATIC006=`009,005,330,010,VARYTEXT,"VaryText_1",progress,DEFAULT,DEFAULT,11,DEFAULT,"Microsoft Sans Serif|6963|40|34","255|0|0",DEFAULT`

ButtonPushed=Dialog("WBOMATIC")

objObjectSet = 0
objSecurity = 0
objService = 0
objLocator = 0

Exit

Article ID:   W16283
File Created: 2011:06:01:12:18:50
Last Updated: 2011:06:01:12:18:50