0

I have created a function in PowerShell mostly is working fine but there are some times that it doesn't, the function is supposed to delete some folders with including files some of them may have more than 200k files the error that I am getting is "folder is not empty". Which is correct. there is something on that folder that needs to be deleted too. But what I can't understand is why sometimes it deletes everything and sometimes not.

I am using VMware for my test when I run the script and to test it. After the script finishes and there is no error and everything has been deleted, I am restoring VM to his previous state from a snapshot then run the script again and the result is that it may fail without a reason.

When I am saying failing I mean that it may leave one empty folder with no files inside.

function Delete {
    if (Test-Path $($args[0])) {
        Write-Host -ForegroundColor Yellow "Deleting $args"

        Get-ChildItem -Path $args -Recurse -Force | Where-Object {
            -not ($_.PSIsContainer)
        } | Remove-Item -Force
        Remove-Item $args -Recurse -Force
    } else {
        Write-Host -ForegroundColor Red "$args  Does not exist"
    }
}

Delete "C:\Backup1"
Delete "C:\Backup2"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
NGs
  • 3
  • 1
  • 3
  • it can take a short time for a delete to be fully done. you may need to add a short delay before removing the directory. ///// however, i would change your code to use robocopy and mirror the tree against a blank source location. that will handle the delete for you - and likely be far faster. [*grin*] – Lee_Dailey May 05 '19 at 21:19
  • Thank you for your answer I am new with PowerShell was thinking that robocopy is to copy or mirror files – NGs May 05 '19 at 21:30
  • 2
    [Maybe related](https://stackoverflow.com/q/53207678/1630171) (see specifically mklement0's answer). – Ansgar Wiechers May 05 '19 at 21:43
  • yes, robocopy is for "robust copy". [*grin*] however, it has a mirror setting that will mirror a blank directory to a whole directory tree ... and that deletes the target tree since it is mirroring _nothing_. – Lee_Dailey May 05 '19 at 21:51
  • Empty the folder and reuse it instead of removing the folder itself. This is just a workaround which might not work seamlessly because the bug is with Windows API call and it is for everything which is related to delete (cmd, DOT Net and PS) – Ranadip Dutta May 06 '19 at 06:14
  • Working with a directory containing [more than 50k files](https://support.microsoft.com/en-us/help/2539403/system-may-pause-while-accessing-large-ntfs-folder) is known to be slow. – vonPryz May 06 '19 at 06:25

0 Answers0