powershellnetwork-drivedrive-mapping

How to obtain UNC drive info on "Disconnected Network Drive"


We run some processes in a distributed computing environment. Processes on one machine need to communicate information with processes on other machines. One of those piecies of information is the location of certain files. Thus, a process on one machine may have put information into a particular file on a particular network share, and it needs to communicate the location to a process on another machine.

We have no problem with the communication part. The problem is with determining the "location" information that a machine need to disseminate. File paths involving drive mappings are clearly useless: different machines will have differing drive mappings. Thus, what we need to communicate it the full UNC path name.

For the most part, we can obtain that information easily. One place where we are having problems is in a powershell script that needs to obtain this information. Currently, we use the following code:

$l_logicalDisk = Gwmi Win32_LogicalDisk -filter "DeviceID = '$l_currentDrive'"
if ( $l_logicalDisk.DriveType -eq 4 )
{
    $l_base = $l_logicalDisk.ProviderName
}

and $l_base provides the \\computername\share information. However, in certain circumstances, this fails. At times, for some unknown reason, a mapped drive will appear as "Disconnected Network Drive" in Explorer.exe, even though the drive and all its files are accessible. (In fact, the script that is running is even located on the supposed "Disconnected Network Drive".) In this situation, the ProviderName field of the logical disk information is blank. Nothing seems to flip the status from "Disconnected Network Drive", nor have I found any way to update the ProviderName information.

So, does anyone know either (1) how to "reconnect" a disconnected network drive from within powershell or (2) how in Powershell to obtain the UNC path information for a directory in a more reliable method that outlined above? Thanks.


Solution

  • You can always ask the registry, this should work on disconnected drives (where $DrvLtr equals the desired network mapped drive letter such as Z or M):

    Pushd
    cd HKCU:
    $UNC=(gci network|?{$_.Name -match "$DrvLtr"}|%{Get-ItemProperty -Path $_}).RemotePath
    Popd
    

    $UNC should then be a string with a value like "\Server01\FileShare$" which I think is what you're going for. Then you can just do a

    $Path.Replace("$DrvLtr`:",$UNC)
    

    And you're all set