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"