Disconnect a mapped network drive in windows using COM

BenWard 0 Tallied Votes 613 Views Share

I had to map a network drive with specific credentials in my PHP script and it kept falling over because I'd already navigated to the drive in windows explorer.
This snippet will unmap a network drive using COM regardless of whether or not there is a drive letter associated with it or not. I can call this bit of code before I attempt the mapping to make sure that the program doesn't fall over.


$UNCPATH = "\\\\server\\share";

//connect to the network object
$network = new COM("wscript.network");
$drives = $network->EnumNetworkDrives();
$limit = 0;
$driveArray = Array();
$driveKey = false;

//get all the drives
while ($limit < $drives->Count()){
  $driveLetter = $drives->item($limit++);
  if (!$driveLetter)
    $driveLetter = $limit;
  $driveArray = array_merge($driveArray,Array($driveLetter => $drives->item($limit++)));

//search for it
foreach ($driveArray as $key => $drive){
  if (strtolower($UNCPATH) == strtolower($drive)){
    $driveKey = $key;

if (is_numeric($driveKey))
  $driveKey = $driveArray[$driveKey];

if (!$driveKey){
  echo "Drive not mapped, cannot unmap it!";

echo "Drive unmapped."