Visual Basic WMI System Services
Win32_LogicalDisk: WMI Method to Invoke Chkdsk
     
Posted:   Thursday March 07, 2002
Updated:   Monday December 26, 2011
     
Applies to:   VB5, VB6
Developed with:   VB6, Windows XP
OS restrictions:   Windows XP or later
Author:   VBnet - Randy Birch
     

Related:  

Win32_LogicalDisk: WMI Method to Invoke Chkdsk
Win32_DiskDrive: WMI Disk Drive Information
Win32_LogicalDisk: WMI Logical Disk Information
     
 Prerequisites
Microsoft XP or later.

A reference set in Projects / References to the Microsoft WMI Scripting Library.


Besides returning system information, the Windows Management Instrumentation classes also expose methods that can be called from VB. In addition, the WMI supports the executing of SQL-style calls to retrieve specific information.

This demo shows how to perform a chkdsk against specific local fixed disks.  The demo starts by pressing the Load Controls button, which passes a SQL string specifying we only want the LogicalDiskSet to return local fixed drives (DriveType 3). For each disk returned, the code loads, positions and captions a checkbox (right-aligned) and a label.  On pressing the Run Chkdsk button, the code again retrieves the local fixed drives and again loops through them, comparing the drive letter (as a double-check) and checking for the corresponding check box to have a value of 1. If matched, the code calls the Chkdsk method, returning a string representing the success of the action.

You will note from the illustration that on my XP box the FAT32 partition returned as an unknown file system. I'd like to hear from others with FAT and FAT32 partitions who try this code to see if you get the same response for the non-NTFS drives.

And now, the caveats.  Because this is a method called against a dataset returned from GetObject, it suffers the same limitations as using GetObject against MS Word or Excel ... if the chkdsk is running, and you click the form, the "Busy" dialog appears with the Switch To... option. So like all other GetObject methods, this too can not be interrupted once processing begins. This also means that your app may not repaint immediately if covered/uncovered. There is no workaround, as there is no place to stick a DoEvents... one Chkdsk is called, it must complete.

I did not try with any but the default flags set (well actually, my initial tests were with all Chkdsk parameters False), so I can't comment on the effectiveness of the forced dismount or OK to schedule flags.

Note: The MSDN states this method is applicable to NT-based systems only.

For a complete listing of the information available by this class, see the table in the Comments section below. Note that some systems may not return information in all class properties.

 BAS Module Code
None.

 Form Code
To a form add two command buttons (Command1, Command1).  Add a checkbox with an index of 0 (Check1(0)), and a label the same (Label(0)). Assure a reference to the Microsoft WMI Scripting Library is set in Projects / References, and add the following to the form:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub Form_Load()

   Command1.Caption = "Load Controls"
   Command2.Caption = "Run Chkdsk"

End Sub


Private Sub Command1_Click()

  'enumerates through all fixed local
  'drives and creates a label and
  'checkbox for each available local drive
  
   Dim LogicalDiskSet As SWbemObjectSet
   Dim disk As SWbemObject
   Dim msg As String
   Dim ssql As String
   Dim cnt As Long
   Dim x As Long
   
   ssql = "select Name from Win32_LogicalDisk where DriveType=3"
   Set LogicalDiskSet = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery(ssql)
   
   For Each disk In LogicalDiskSet
   
     'create a checkbox and label
     'for each local fixed drive
     
     'since array elements(0) already
     'exists, don't try to load it
      If cnt > 0 Then
         Load Check1(cnt)
         Load Label1(cnt)
      End If
   
     'Position the new controls.
     'Since I hard-coded the offsets and I develop 
     'at 1280 with small fonts, the values below 
     'may need tweaking for systems with different 
     'settings to position and align the loaded controls.
      With Check1(cnt)
         .Move 240, 300 + (cnt * 360), 600
         .Caption = disk.Name
         .Enabled = True
         .Visible = True
         .Alignment = 1
         .Value = 0
      End With
      
      With Label1(cnt)
         .Move Check1(cnt).Left + Check1(cnt).Width + 100, 300 + (cnt * 360), 2500
         .AutoSize = True
         .Enabled = True
         .Visible = True
         .Caption = "not included"
      End With
      
      cnt = cnt + 1
   Next
   
  'prevent reloading of controls
   Command1.Enabled = False
   
  'clean up
   Set disk = Nothing
   Set LogicalDiskSet = Nothing
   
End Sub


Private Sub Command2_Click()

   Dim LogicalDiskSet As SWbemObjectSet
   Dim disk As SWbemObject
   Dim ssql As String
   Dim cnt As Long

  'return a reference to the fixed disks
   ssql = "select Name,FileSystem from Win32_LogicalDisk where DriveType=3"
   Set LogicalDiskSet = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery(ssql)

   If LogicalDiskSet.Count > 0 Then
      
     'loop through each returned disk
      For Each disk In LogicalDiskSet
                    
        'if the disk matched the
        'checkbox caption and the
        'checkbox was selected,
        'perform chkdsk against the drive
         If disk.Name = Check1(cnt).Caption And _
                        Check1(cnt).Value = 1 Then
            
           'since this can take a while
           'indicate process has started
            Label1(cnt).Caption = "Running chkdsk against drive " & _
                                  disk.Name & " ... please wait."
            Label1(cnt).Refresh
            
           'show result of call
            Label1(cnt).Caption = Chkdsk(disk) & "  (" & disk.FileSystem & ")"

         End If
         
         cnt = cnt + 1
         
      Next

   End If
   
  'clean up
   Set disk = Nothing
   Set LogicalDiskSet = Nothing

End Sub


Private Sub Check1_Click(Index As Integer)

   If Check1(Index).Value = 1 Then
      Label1(Index).Caption = "waiting to run command"
   Else
      Label1(Index).Caption = "not included"
   End If
   
End Sub


Private Function Chkdsk(disk As SWbemObject) As String

  'chkdsk method parameters:
  '----------------------------
  'FixErrors : boolean
  'Indicates what should be done to errors found
  ' on the disk. If true, then errors are fixed.
  'The default is FALSE.
  '
  'VigorousIndexCheck : boolean
  'If TRUE, a vigorous check of index
  'entries should be performed.
  'The default is TRUE.
  '
  'SkipFolderCycle : boolean
  'If TRUE, the folder cycle checking
  'should be skipped or not.
  'The default is TRUE.
  '
  'ForceDismount : boolean
  'If TRUE, the drive should be forced
  'to dismount before checking.
  'The default is FALSE.
  '
  'RecoverBadSectors : boolean
  'If TRUE, the bad sectors should be located
  'and the readable information should be
  'recovered from these sectors.
  'The default is FALSE.
  '
  'OKToRunAtBootUp : boolean
  'If TRUE, the chkdsk operation should
  'be performed at next boot up time, in
  'case the operation could not be performed
  'because the disk was locked at time
  'the method was called. The default is FALSE.

   Select Case disk.Chkdsk(False, True, True, False, False, False)
      Case 0: Chkdsk = "Success - chkdsk completed"
      Case 1: Chkdsk = "Success - Disk locked - chkdsk scheduled on reboot"
      Case 2: Chkdsk = "Unknown file system"
      Case 3: Chkdsk = "Unknown error"
   End Select

End Function
 Comments
All information returned in the Win32_LogicalDisk class (note that some systems may not return information in all class properties):
   
uint16 Access
uint16 Availability
uint64 BlockSize
string Caption
boolean Compressed
uint32 ConfigManagerErrorCode
boolean ConfigManagerUserConfig
string CreationClassName
string Description
string DeviceID
uint32 DriveType
boolean ErrorCleared
string ErrorDescription
string ErrorMethodology
string FileSystem
uint64 FreeSpace
datetime InstallDate
uint32 LastErrorCode
uint32 MaximumComponentLength
uint32 MediaType
string Name
uint64 NumberOfBlocks
string PNPDeviceID
uint16 PowerManagementCapabilities[]
boolean PowerManagementSupported
string ProviderName
string Purpose
boolean QuotasDisabled
boolean QuotasIncomplete
boolean QuotasRebuilding
uint64 Size
string Status
uint16 StatusInfo
boolean SupportsDiskQuotas
boolean SupportsFileBasedCompression
string SystemCreationClassName
string SystemName
boolean VolumeDirty
string VolumeName
string VolumeSerialNumber

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter