Check if a drive is mapped and active

4.7k views Asked by At

I have a requirement within my VBScript to ensure that a drive is mapped and contactable.

Initially I was using only the DriveExists() method of the FileSystemObject, but this fell short as in certain scenarios users start the day in the office but then take their laptops on tour, without shutting down; thus the drive in question is still listed as mapped, but is not contactable.

To Address this I have created the below function, but it seems a bit dirty due to the use of On Error Resume Next.

So my question is this; is there a method that achieves my goal built in to VBS, or is my approach (or similar) the only way it can be done?

Function CheckDriveExists(drive)

    CheckDriveExists = false

    If FSO.DriveExists(drive) Then  ' A drive is mapped for the required 'drive'

        '** Create a file name for the test file *'
        Dim tfDate, tfName
        tfDate = Year(Now) & Month(Now) & Day(Now) & Hour(Now) & Minute(Now) & Second(Now)
        tfName = "tstfile-" & tfDate & ".bucf"

        '** Try to create and then delete a file on the usrs backup drive *'
        On Error Resume Next
        FSO.CreateTextFile(drive & ":\" & tfName)
        FSO.DeleteFile(drive & ":\" & tfName)

        CheckDriveExists = (Err.Number = 0) ' Check to see if the file was created and deleted successfully
        Err.Clear                           ' Clear any possible error              
        On Error GoTo 0                     ' Reset error handling

    End If

End Function
1

There are 1 answers

0
Zam On BEST ANSWER

from Windows Scripting documentation

Function ShowDriveList
   Dim fso, d, dc, s, n
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set dc = fso.Drives
   For Each d in dc
      n = ""
      s = s & d.DriveLetter & " - " 
      If d.DriveType = 3 Then
         n = d.ShareName
      ElseIf d.IsReady Then
         n = d.VolumeName
      Else
         n = "[Drive not ready]"
      End If
      s = s & n & "<BR>"
   Next
   ShowDriveList = s
End Function

perhaps you also need

Function ShowDriveType(drvpath)
   Dim fso, d, t
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(drvpath)
   Select Case d.DriveType
      Case 0: t = "Unknown"
      Case 1: t = "Removable"
      Case 2: t = "Fixed"
      Case 3: t = "Network"
      Case 4: t = "CD-ROM"
      Case 5: t = "RAM Disk"
   End Select
   ShowDriveType = "Drive " & d.DriveLetter & ": - " & t
End Function