无法删除项目。目录不为空

Cannot remove item. The directory is not empty

我正在尝试删除包含 subfolders/files 的文件夹。

Remove-Item -Force -Recurse -Path $directoryPath

我遇到错误 Cannot remove item. The directory is not empty.

我的 PowershellScript.ps1 具有 executionPolicy unrestricted。 我尝试使用当前登录用户删除的根文件夹对此文件夹具有 完全权限

代码在我的本地电脑上有效,但在我的 Windows Server 2012 R2.

上无效

您可以尝试以下方法:

Remove-Item -Force -Recurse -Path "$directoryPath\*"

请注意,在 Remove-Item 中将 -Recurse 参数与 -Include 一起使用时,它可能不可靠。所以最好先用 Get-ChildItem 递归文件,然后通过管道输入 Remove-Item。如果您删除大型文件夹结构,这也可能有所帮助。

Get-ChildItem $directoryPath -Recurse | Remove-Item -Force   

文件已在另一个程序中打开

我忘记了我已经 Visual Studio 打开我的项目并收到此错误。

关闭与该目录关联的所有文件,运行 PowerShell 以管理员身份,然后 运行 命令:

Remove-Item "C:\path\to\dir" -Recurse -Force

专业提示

您也可以运行此命令打开文件资源管理器:

ii "C:\path\to\dir"

如果您右击并尝试删除它,它可能给您一个比命令行更详细的错误。

这对我有用,我删除了比我年还早的文件和文件夹,递归地包括文件夹。

Get-ChildItem -目录 -路径 X:\AutomateCache | where-Object {$_.Lastwritetime -ile (get-date).AddMonths(-12) } |删除项目 -Force -Recurse -Verbose

注意

Remove-Item -Force -Recurse -Path "C:\MyFolder"

产生这个错误,但是

Remove-Item -Force -Recurse -Path "C:\MyFolder\*"

不是

所以别忘了魔法酱

这种方式每次都有效, 它按降序对文件和目录进行排序,以确保首先删除目录结构中最深的成员。

Get-ChildItem $output_path -File -Recurse | Sort-Object FullName -Descending | Remove-Item -Force -Confirm:$false;
Get-ChildItem $output_path -Directory -Recurse | Sort-Object FullName -Descending | Remove-Item -Force -Confirm:$false;
Remove-Item $output_path -Force;