Remove-PSDrive 不会删除驱动器

Dir*_*irk 6 powershell

我使用 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
Run Code Online (Sandbox Code Playgroud)

现在我想更换驱动器并通过以下方式断开它们:

Get-PSDrive -Name L, I -ErrorAction SilentlyContinue | Remove-PSDrive -Scope Global -Force
Run Code Online (Sandbox Code Playgroud)

如果没有,-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
Run Code Online (Sandbox Code Playgroud)

不幸的是,所有驱动器(包括 L)都没有被移除或断开。我通过检查这个net use并得到:

Getrennt   I:   \\Server\whatever                    Microsoft Windows Network
OK         L:   \\localhost\C$\...\Documents\wrong   Microsoft Windows Network
Run Code Online (Sandbox Code Playgroud)

您知道为什么Remove-PSDrive不履行其职责吗?

小智 7

我遇到了同样的问题,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

}
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一种可能性。然而,令我惊讶的是,这不适用于 PS 本身。 (3认同)

小智 6

对我来说,一个更简洁的解决方案是使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)