Disconnect a mapped network drive in windows using COM

BenWard 0 Tallied Votes 617 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.

<?php


$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;
    break;
  }
}

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

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

$network->RemoveNetworkDrive($driveKey);
echo "Drive unmapped."

?>