0

I'm trying to recursively delete all files and folders inside of a folder with Powershell via:

 Foreach ($File in $ListFicher)
            {                  
                if ($?)
                  {
                  try{
                     Remove-Item -force  $File -recurse  -Verbose $ErrorActionPreference = "Continue"
                     }
                     catch  {  write-host "the $File directory can't not deleted"
                     
                           }    
                      }    
            }

I want when he can't delete a file, example he is locked, that he continues and deletes the others, but he does not do that for the moment he does not show me an error he continues but does not delete the rest of the files. thank you

said Boua
  • 23
  • 3
  • 1
    Change `$ErrorActionPreference = "Continue"` to `-ErrorAction "Continue"` and it should work fine. Keep in mind that Try/Catch does not work unless the error is a stopping error, so selecting Continue for the ErrorAction means that it will never trigger the Catch scriptblock. – TheMadTechnician Feb 28 '23 at 15:54
  • hi I changed the statement and added -ErrorAction "Continue" , and I have an error and can't continue to other files Error is "The \\... directory cannot be deleted because it is not empty." and can not Continue to – said Boua Feb 28 '23 at 16:30
  • Search for tail recursion here on SO to fix the "folder not empty" issue – Scepticalist Feb 28 '23 at 16:51
  • Incredibly, the Windows API has _historically_ been _asynchronous_ with respect to file / directory deletion, causing recursive deletion of adirectory tree to fail _intermittently_. Therefore, all shells / APIs that build on the Windows API used to failed intermittently: PowerShell, cmd, .NET. Fortunately, since (at least) Windows 10 20H2, the Windows API is now _synchronous_, which made the problem go away, except - curiously - in cmd. See [this answer](https://stackoverflow.com/a/53561052/45375) for more information. – mklement0 Feb 28 '23 at 16:57

1 Answers1

0

This may seem a little convoluted but it does work! See comments in code for logic.

Clear-Host

#*** Setup ***
$BasePath = "N:\Scripts"
$DeletedFiles    = 0
$NonDeletedFiles = 0
$DeletedDirs     = 0
$NonDeletedDirs  = 0


#Gather all directories under $BasePath
$GCIArgs = @{Path      = "$BasePath"
             Directory = $True
             Recurse   = $True
            }
[System.Collections.ArrayList]$Dirs = (Get-ChildItem @GCIArgs).FullName
[Void]$Dirs.Add("$BasePath")  #Add base path to deletion list!

#Sort dirs longest first to allow deletion in proper order
$SDirs = $Dirs | Sort-Object { $_.length } -Descending

For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++) {

  $GCIArgs = @{Path = "$($SDirs[$($Cntr)])"
               File = $True
               ErrorAction = "SilentlyContinue"
              }
                $FilesToDel = Get-ChildItem @GCIArgs

  If ($Null -ne $FilesToDel) {
  
    ForEach ($File in $FilesToDel) {
      $RIArgs = @{LiteralPath = "$($File.FullName)"
                  Force       = $True
                  ErrorAction = "Stop"
                 }
  
      Try { 
            Remove-Item @RIArgs
            $DeletedFiles += 1   
          }
      Catch {
              "Could not delete File: $File "
              $NonDeletedFiles += 1
            }
  
    } #End ForEach ($File in $FilesToDel)

  } #End If ($FilesToDel.Count -gt 0)
  
  #Remove the containing Directory!

  Try {
       $RIArgs.LiteralPath = "$($SDirs[$($Cntr)])"
       #Note -Recurse necessary to prevent popup msg reporting
       #     child directories when none exist, not sure why?
       Remove-Item @RIArgs -Recurse
       $DeletedDirs += 1
      }
  Catch {
          "Could not Delete Directory: $($SDirs[$($Cntr)])"
          $NonDeletedDirs += 1
  }              
  
} #End For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++)

"`nRun Statistics:"
"$DeletedDirs Directories were Deleted"
"$DeletedFiles Files were Deleted"
"$NonDeletedDirs Directories could NOT be Deleted"
"$NonDeletedFiles Files could NOT be Deleted!"

Sample Output:

Run Statistics:
135 Directories were Deleted:
2243 Files were Deleted
0 Directories could NOT be Deleted
0 Files could NOT be Deleted!

Note: before I got the bugs out I was getting messages about files and directories that could not be deleted.

RetiredGeek
  • 2,980
  • 1
  • 7
  • 21