我想删除网络共享上的配置文件文件夹时遇到问题。某些无法删除的文件夹似乎存在问题。
以下是代码,在大多数文件夹上都可以正常工作:
Import-Module -Name 'C:UsersmkzDocumentspowershellmodulesAlphaFS.2.1.3.0LibNet452AlphaFS.dll'
$folder = "\filsrvmMDrevfolderName"
#Function to take ownership and grant permissions
function takeOwnership($path)
{
if(Test-Path $path)
{
$server = ($path).Split("\",5)[2]+".adm.domain.dk"
takeown.exe /S $server /F $path /r /d Y
icacls $path /grant 'GroupAdm_GL:(CI)(OI)F' /t /c /q
icacls "$path*" /reset /t /c /q
}
}
#Function to delete folders
function deleteFolder($path)
{
if(Test-Path $path)
{
[Alphaleonis.Win32.Filesystem.Directory]::Delete($path, $true, $true)
}
}
takeOwnership($folder)
deleteFolder($folder)
我收到以下错误:
<red>Exception calling "Delete" with "3" argument(s): "(145) The directory is not empty: [\?UNCfilsrvmMDrevfolderNameCtx]"
At C:UsersmkzDocumentspowershellsingleDelete.ps1:24 char:9
+ [Alphaleonis.Win32.Filesystem.Directory]::Delete($path, $true ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DirectoryNotEmptyException</red>
我尝试使用Remove-Item $path -force -Recurse
而不是"Alphaleonis",但它会导致相同的错误。
我还没有找到在PowerShell中本机执行此操作的方法。这个解决方案在Windows Server 2012 R2上对我有用。它大致转换为 PS 为:
$pathToDelete = "TROUBLESOME_PATH_ROOT"
$tmpDir = [System.IO.Path]::GetRandomFileName()
mkdir $tmpDir
& robocopy.exe /S /MIR $tmpDir "$pathToDelete"
rmdir $tmpDir
rmdir "$pathToDelete"
这会递归地将空目录镜像到目标目录,从而有效地将其删除。
另请参阅如何删除路径/名称太长而无法正常删除的目录。