【问题标题】:Cant delete certain folders with powershell无法使用powershell删除某些文件夹
【发布时间】:2023-04-07 07:40:01
【问题描述】:

我想删除网络共享上的配置文件文件夹时遇到问题。某些文件夹似乎有问题,无法删除。

这里是代码,在大多数文件夹上都可以正常工作:

Import-Module -Name 'C:\Users\mkz\Documents\powershell\modules\AlphaFS.2.1.3.0\Lib\Net452\AlphaFS.dll'

$folder = "\\filsrvm\MDrev\folderName"

#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: [\\?\UNC\filsrvm\MDrev\folderName\Ctx]"
At C:\Users\mkz\Documents\powershell\singleDelete.ps1:24 char:9
+         [Alphaleonis.Win32.Filesystem.Directory]::Delete($path, $true ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DirectoryNotEmptyException</red>

我尝试使用Remove-Item $path -force -Recurse 代替“Alphaleonis”,但会导致同样的错误。

【问题讨论】:

    标签: powershell powershell-3.0 powershell-4.0 icacls


    【解决方案1】:

    我还没有找到在 PowerShell 中本地执行此操作的方法。 This solution 在 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"
    

    这会递归地将一个空目录镜像到目标目录,从而有效地删除它。

    另见How to delete directories with path/names too long for normal delete

    【讨论】:

    • 我试过了,但我得到一个错误。 rmdir : Parts of the path '\\filsrvm\filepath\to\remove' wasnt found.
    • 听起来 RoboCopy 已成功完成。根据我引用的链接,您可能需要多次运行它,尽管我自己没有遇到这个问题。 $pathToDelete 中是否还有文件?
    • 抱歉回复晚了,但是$pathToDelete 中仍有文件。我曾多次尝试运行它,但似乎没有任何效果。当我获得所有权后运行 robocopy 时,出现以下错误:2018/07/17 08:18:52 ERROR 2 (0x00000002) Deleting Extra Directory \\folder\to\delete The specified file was not found.
    • 如果在上面的$pathToDelete 参数周围加上引号会怎样?
    • 你的意思是像这样围绕变量:“$pathToDelete”?有什么区别?
    猜你喜欢
    • 2014-11-08
    • 2017-05-06
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多