PowerShell Remove-Item not waiting

后端 未结 4 1645
不知归路
不知归路 2021-01-13 05:20

If have this piece of code

if(Test-Path -Path $OUT) 
{ 
    Remove-Item $OUT -Recurse 
}
New-Item -ItemType directory -Path $OUT

Sometimes

4条回答
  •  北海茫月
    2021-01-13 05:49

    The Remove-Item command has a known issue.

    Try this instead:

    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
    }
    

    Note:

    • 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.

    • Similarly, add -Force to -RemoveItem to force removal of files that have the read-only attribute set.

      • 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.

提交回复
热议问题