我正在尝试删除包含子文件夹/文件的文件夹。
Remove-Item -Force -Recurse -Path $directoryPath
我收到错误Cannot remove item. The directory is not empty.
我的 PowershellScript.ps1 executionPolicy不受限制。 我尝试使用当前登录用户删除的根文件夹在此文件夹中具有完全权限。
在我的本地电脑上,代码可以正常运行,但不在我的Windows Server 2012 R2
上。
答案 0 :(得分:30)
您可以尝试以下方法:
Remove-Item -Force -Recurse -Path "$directoryPath\*"
但-Recurse
中的Remove-Item
参数始终无法正常工作,因此最好先使用Get-ChildItem
递归文件,然后将其传递给Remove-Item
。< / p>
Get-ChildItem $directoryPath -Recurse | Remove-Item -Force
答案 1 :(得分:3)
文件已在另一个程序中打开
我忘了我在打开项目的同时打开了Visual Studio,却遇到了此错误。
关闭与该目录关联的所有文件,以admin身份运行PowerShell,然后运行以下命令:
Remove-Item "C:\path\to\dir" -Recurse -Force
答案 2 :(得分:0)
这对我有用,我删除了较旧的文件和文件夹,然后递归包括文件夹。
Get-ChildItem -Directory -Path X:\ AutomateCache | where对象{$ _。Lastwritetime -ile(get-date).AddMonths(-12)} | Remove-Item -Force -Recurse -Verbose
答案 3 :(得分:0)
注意
Remove-Item -Force -Recurse -Path "C:\MyFolder"
产生这个错误,但是
Remove-Item -Force -Recurse -Path "C:\MyFolder\*"
不是。
所以别忘了魔法酱