我使用 Powershell > 4 在计算机上创建和删除驱动器。我将它们本地连接到文件夹或远程驱动器:
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
现在我想更换驱动器并通过以下方式断开连接:
Get-PSDrive -Name L, I -ErrorAction SilentlyContinue | Remove-PSDrive -Scope Global -Force
如果没有
-ErrorAction
,我会收到以下关于当前无法访问的网络驱动器的消息:
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
不幸的是,所有驱动器(包括 L)都没有被移除或断开。我通过
net use
检查并得到:
Getrennt I: \\Server\whatever Microsoft Windows Network
OK L: \\localhost\C$\...\Documents\wrong Microsoft Windows Network
你知道为什么
Remove-PSDrive
没有完成它的工作吗?
我遇到了与Remove-PSDrive相同的问题,没有删除任何网络驱动器,也没有输出任何错误,所以我通过使用powershell和旧的“net use”的组合解决了这个问题
$psdrive = psdrive | Where { $_.DisplayRoot -like '\\*' }
foreach ($mapdrive in $psdrive){
if($mapdrive.DisplayRoot -Like '\\NetworkPath\folder\etc*'){
$driveLetter = ($mapdrive.Root) -replace "\\",""
$drivePath = $mapdrive.DisplayRoot
Write-Host "Removing drive $driveLetter with path $drivePath" -foregroundcolor green
net use $driveLetter /delete
}
}
对我来说,一个更简洁的解决方案是使用Remove-SmbMapping 和New-SmbMapping 代替。此代码按预期工作:
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
}
}
试试这个方法。我无法单独使用以下命令来使其工作,但最终它一起正确地清除了映射。我认为这可能与映射驱动器时的“Persist”参数有关(但根据 MS 文档删除时这并不重要)。我使用了 Try..Catch 块(不是最优雅的),但是如果您在驱动器已被删除后尝试再次运行它,则此方法确实会抱怨驱动器不存在。
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
{
}
在 WinOS 中挂载股票的方法有很多种 - 利用
Get-PSDrive
、Get-SmbMapping
、Get-SmbGlobalMapping
、net use
等来列出现有股票。确保以管理员身份运行 powershell.exe
并运行与创建挂载方式相关的 removla 命令。您不需要触摸注册表来寻找 MountPoints2
- 这是一个 hack。
Remove-SmbGlobalMapping K:
Remove-SmbMapping K:
Remove-PSDrive K
net use K: /delete
阅读完以上所有内容后,唯一对我持续有效的就是。
删除-SmbMapping -LocalPath“K:”-强制