Re: EnumNetworkDrives and RemoveNetworkDrive doesn't work on broken network connection / share - any other ways? by drlandau
drlandau
Tue Feb 21 03:37:28 CST 2006
Hmm, odd enough the EnumNetworkDrives 'sometimes' seem to work, but
this may be because the connection isn't always being reported as
broken immediately...(?) Anyway the RemoveNetworkDrive function seems
to work if you set both bForce and bUpdateProfile to TRUE - but as
EnumNetworkDrives obviously can't be trusted to show all drives if some
are broken, the following code won't work:
<pre>
' Return true if the specified driveletter is currently mapped to a
network drive or otherwise in use
Function DriveletterInUse(strDriveLetter)
Dim objWshNetwork, objDrives, intCounter, blnDriveletterInUse, objFSO
Set objWshNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objDrives = objWshNetwork.EnumNetworkDrives
blnDriveletterInUse = False
For intCounter = 0 to objDrives.Count - 1 Step 2
If UCase(Left(objDrives.Item(intCounter), 1)) =
UCase(Left(strDriveLetter, 1)) Then blnDriveletterInUse = True
Next
If objFSO.DriveExists(strDriveLetter) Then blnDriveletterInUse = True
DriveletterInUse = blnDriveletterInUse
End Function
</pre>
Instead I've written a function that uses WMI to check if the
driveletter is in use, as WMI (Win32_NetworkConnection) returns the
connection information even though the connection is broken
(driveletter and networkpath is returned along with the state of the
connection, error, disconnected, degraded etc.). Use this function to
check if a driveletter is in use - and then use the RemoveDriverLetter
function with both bForce and bUpdateProfile set to TRUE, to delete the
connection. There's not much errorchecking, so if needed incorporate
this yourself:
<pre>
Function DriveletterInUse(strComputer, strDriveLetter)
' Declare variables
Dim objFSO, objWMIService, colNetworkConnections
' Define constants
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
' Create objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("winmgmts:\\" & strComputer &
"\root\CIMV2")
Set colNetworkConnections = objWMIService.ExecQuery("SELECT * FROM
Win32_NetworkConnection", "WQL", _
wbemFlagReturnImmediately + wbemFlagForwardOnly)
' Assume driveletter is not in use by default
blnDriveletterInUse = False
' Loop through all network connections
For Each objNetworkConnection In colNetworkConnections
' Check network connections
If UCase(Left(objNetworkConnection.LocalName, 1)) =
UCase(Left(strDriveLetter, 1)) Then blnDriveletterInUse = True
Next
' Use FileSystemObject to include checking of local driveletters
If objFSO.DriveExists(strDriveLetter) Then blnDriveletterInUse = True
' Return boolean value
DriveletterInUse = blnDriveletterInUse
' Cleanup
Set objFSO = Nothing
Set objWMIService = Nothing
Set colNetworkConnections = Nothing
End Function
</pre>
Sorry for any bugs!
Best regards,
Nicolaj