0

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.

Edited by BenWard: formatting

<?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."

?>
1
Contributor
0
Replies
14
Views
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.