Search code examples
powershellfilesystemssynchronousntfs

PowerShell Remove-Item not waiting


If have this piece of code

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

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 I insert a sleep there

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

then it works always. How can I force Remove-Item to ensure that the folder is really removed? Or maybe I miss something else?


Solution

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