I use Powershell > 4 to create and remove drives on my computer. I connect them locally to a folder or to remote drives:
New-PSDrive -Name L -PSProvider FileSystem -Root ($userprofile + "\Documents\whatever") -Scope Global -Persist
New-PSDrive -Name I -PSProvider FileSystem -Root \\server\whatever -Scope Global -Persist -Credential $usercred
Now I would like to change the drives and disconnect them via:
Get-PSDrive -Name L, I -ErrorAction SilentlyContinue | Remove-PSDrive -Scope Global -Force
Without -ErrorAction I get the following message for the network drives which are currently not reachable:
Get-PSDrive : The drive was not found. A drive with the name "I" does not exist.
In Zeile:1 Zeichen:1
+ Get-PSDrive -Name L, I -Scope ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (I:String) [Get-PSDrive], DriveNotFoundException
+ FullyQualifiedErrorId : GetDriveNoMatchingDrive,Microsoft.PowerShell.Commands.GetPSDriveCommand
Unfortunately, all drives (including L) are not removed or disconnected. I check this via net use and get:
Getrennt I: \\Server\whatever Microsoft Windows Network
OK L: \\localhost\C$\...\Documents\wrong Microsoft Windows Network
Do you have an idea why Remove-PSDrive does not do its job?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With