1

I have a powershell script with a remove-item -recurse statement inside the try catch blocks that fails on a file in the path, but does not throw an exception.

        try{
            remove-item $jobfolder -Recurse
            log-entry "SUCCESS: Removed job folder $jobfolder"
            return $true
        }
        catch{
            log-entry "FAILED: Failed to delete job folder $jobfolder $_"
            return $false
        }

When this executes, I get a permission error on a file,

remove-item : Cannot remove item \srv1\archive\12556\thumbs.db: You do not have sufficient access rights to perform this operation. At C:\powershellScripts\ssl-jobarchives.ps1:121 char:9

  •     remove-item $jobfolder -Recurse
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : PermissionDenied: (Thumbs.db:FileInfo) [Remove-Item], IOException
    • FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand remove-item : Directory \srv1\archive\12556 cannot be removed because it is not empty. At C:\powershellScripts\ssl-jobarchives.ps1:121 char:9
  •     remove-item $jobfolder -Recurse
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : WriteError: (\srv1\archive\12556:DirectoryInfo) [Remove-Item], IOException
    • FullyQualifiedErrorId : DirectoryNotEmpty,Microsoft.PowerShell.Commands.RemoveItemCommand

but the exception is not caught, and my log file does not contain the error, nor does the function return false like I want it to.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Try adding "-ErrorAction Stop" to the Remove-Item command to force the error to be a terminating error – Mike Shepard Nov 10 '20 at 21:09
  • In short: What `Remove-Item` emits are _non-terminating_ errors, which cannot be caught with `try` / `catch` - unless you promote them to _terminating_ ones with `-ErrorAction Stop`, as @MikeShepard states - see [this answer](https://stackoverflow.com/a/59641995/45375) to the linked duplicate. – mklement0 Nov 10 '20 at 21:19

0 Answers0