PowerShell Remove-Item不等待 [英] PowerShell Remove-Item not waiting
问题描述
如果有这段代码
if(Test-Path -Path $OUT)
{
Remove-Item $OUT -Recurse
}
New-Item -ItemType directory -Path $OUT
有时可以,但是有时New-Item行会产生 PermissionDenied ItemExistsUnauthorizedAccessError 错误.我认为这意味着以前的Remove-Item尚未完全执行,并且无法创建该文件夹,因为该文件夹仍然存在.
Sometimes it works, but sometimes the New-Item line produces a PermissionDenied ItemExistsUnauthorizedAccessError error. Which, I assume, means that the previous Remove-Item was not completely performed yet and the folder cannot be created because it still exists.
如果我在那里睡觉
if(Test-Path -Path $OUT)
{
Remove-Item $OUT -Recurse
Start-Sleep -s 1
}
New-Item -ItemType directory -Path $OUT
然后它总是可以工作. 如何强制Remove-Item以确保文件夹已真正删除? 还是我想念其他东西?
then it works always. How can I force Remove-Item to ensure that the folder is really removed? Or maybe I miss something else?
推荐答案
Remove-Item
命令具有尝试以下方法:
if (Test-Path $OUT)
{
# if exists: empty contents and reuse the directory itself
Get-ChildItem $OUT -Recurse | Remove-Item -Recurse
}
else
{
# else: create
New-Item -ItemType Directory -Path $OUT
}
注意:
-
Get-ChildItem
命令仅查找非隐藏文件和子目录,因此清空目标目录可能不完整;要也包含隐藏的项目,请添加-Force
.
The
Get-ChildItem
command only finds non-hidden files and subdirectories, so emptying out the target directory may not be complete; to include hidden items too, add-Force
.
类似地,将-Force
添加到-RemoveItem
以强制删除具有只读属性集的文件.
Similarly, add -Force
to -RemoveItem
to force removal of files that have the read-only attribute set.
- 没有
-Force
时,清空可能仍然不完整,但是在这种情况下,您将得到非终止错误.如果要将它们视为终止错误,也请添加-ErrorAction Stop
.
- Without
-Force
, emptying may again be incomplete, but you'll get non-terminating errors in this case; if you want to treat them as terminating errors, add-ErrorAction Stop
too.
这篇关于PowerShell Remove-Item不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!