RobboLew
RobboLew

Reputation: 95

Check shared drive is already mapped

I'm using PowerShell for the first time to check if a unc path is already mapped, and if it is delete it to create it again under specific credentials.

The problem I have found is if the path exists in the net use list but has a drive letter, you have to delete it by the drive letter which can be of course random. So I need to find out the drive letter when I match it but I am clueless as to how.

$userPass = '/user:Domain\User password';
$ltr = ls function:[d-z]: -n | ?{ !(test-path $_) } | random;
$share = '\\\\server\\folder';
$newMap = 'net use '+ $ltr + ' '$share + ' '$userPass;
foreach ($con in net use) {
    if ($con -match $share) {
        $MappedLetter = /*something here to find the matched drive?*/
        if ($MappedLetter) {
            net use $MappedLetter /delete
        } else {
            net use $share /delete
        }
    }
};

net use $newMap;

[Edit]

I have tried the Get-PSDrive but this only works IF the UNC path is mapped to a drive. As these can at times be a "zombie", i.e. exist in net use but have no letter, this method won't always work. I can combine the two methods (above an Get-PSDrive) but if anyone has a cleaner way please let me know!

Upvotes: 2

Views: 2703

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

You should be able to check whether a particular share is already mapped via Get-PSDrive:

$share = '\\server\share'

$drive = Get-PSDrive |
         Where-Object { $_.DisplayRoot -eq $share } |
         Select-Object -Expand Name

if ($drive) {
    "${share} is already mapped to ${drive}."
}

If you just want to remove the drive in case it is mapped you could do something like this:

Get-PSDrive | Where-Object {
    $_.DisplayRoot -eq $share
} | Remove-PSDrive

Update:

AFAIK PowerShell can't enumerate and remove disconnected drives directly. You can obtain that information from the registry:

$share = '\\server\share'
$drive = Get-ItemProperty 'HKCU:Network\*' |
         Where-Object { $_.RemotePath -eq $share } |
         Select-Object -Expand PSChildName

or parse it out of the net use output:

net use | Where-Object {
    $_ -match '(?<=^Unavailable\s+)\w:'
} | ForEach-Object {
    $matches[0]
}

However, from what I know you still won't be able to remove the drive (e.g. via net use) as long as it remains disconnected. For removing a disconnected drive (e.g. when a share has become permanently unavailable) that you'd need to remove the mapping information from the registry:

$share = '\\server\share'
Get-ItemProperty 'HKCU:Network\*' |
    Where-Object { $_.RemotePath -eq $share } |
    Remove-Item

# also remove mount point in Windows Explorer
$key = 'Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
$subkey = Join-Path $key ($share -replace '\\', '#')
Get-ItemProperty "HKCU:${subkey}" | Remove-Item

Upvotes: 8

Related Questions