powershell – Remove-PSDrive does not remove drives

powershell – Remove-PSDrive does not remove drives

I was having the same problem with Remove-PSDrive not removing any network drives and not outputting any error either, so I fixed this problem by using a combination of powershell and the good old net use

$psdrive = psdrive | Where { $_.DisplayRoot -like \* }
foreach ($mapdrive in $psdrive){

if($mapdrive.DisplayRoot -Like \NetworkPathfolderetc*){

$driveLetter = ($mapdrive.Root) -replace \,
$drivePath = $mapdrive.DisplayRoot
Write-Host Removing drive $driveLetter with path $drivePath -foregroundcolor green

net use $driveLetter /delete

}
}

For me a tidier solution was to use Remove-SmbMapping and New-SmbMapping instead. This code works as expected:

Function New-MappedDrive ([Char]$Letter, [string]$Path){
    If (-not (Test-Path -Path $Path)) {
        Write-Host   Unable to map drive $Letter - Invalid path -ForegroundColor Red
    }
    else{
        #Remove existing connections
        if ($($Letter): -in (Get-SmbMapping).LocalPath){Remove-SmbMapping -LocalPath $Letter: -Force | Out-Null}

        New-SmbMapping -LocalPath $Letter: -RemotePath $Path -Persistent $true | Out-Null
    }
}

powershell – Remove-PSDrive does not remove drives

Try this method. I couldnt get this to work either using the below commands separately, but together it finally cleared the mappings properly. Im thinking it might be related to the Persist parameter when mapping the drives (but this isnt supposed to matter when removing according to the MS documentation). I used Try..Catch block (not the most elegant) but this method does complain about drive not present if you try to run it another time after drives are already removed otherwise.

try
{
$mappings_to_remove = Get-PSDrive L, I -ErrorAction SilentlyContinue
Remove-PSDrive $mappings_to_remove -PSProvider FileSystem -Scope Global -erroraction SilentlyContinue | Out-Null
Remove-SMBMapping $mappings_to_remove -Force -erroraction SilentlyContinue | Out-Null
}
catch
{
}

Leave a Reply

Your email address will not be published.