Powershell catch non-terminating errors WITH SilentlyContinue

12,242

You cannot use Try/Catch with ErrorAction SilentlyContinue. If you want to silently handle the errors, use Stop for your ErrorAction, and then use the Continue keyword in your Catch block, which will make it continue the loop with the next input object:

$getPST = Get-ChildItem C:\ -Recurse -File -Filter "*.PST" 
$pstSize = @()
Foreach ($pst in $getPST)
{
 Try {
      If((Get-Acl $pst.FullName -ErrorAction Stop).Owner -like "*$ENV:USERNAME")
       {
        $pstSum = $pst | Measure-Object -Property Length -Sum      
        $size = "{0:N2}" -f ($pstSum.Sum / 1Kb)
        $pstSize += $size
       }
     }

 Catch {Continue}
}
$totalSize = "{0:N2}" -f (($pstSize | Measure-Object -Sum).Sum / 1Kb)
Share:
12,242
HiTech
Author by

HiTech

Updated on June 14, 2022

Comments

  • HiTech
    HiTech almost 2 years

    I would like to catch and handle non-terminating errors but using -ErrorAction SilentlyContiune. I know I need to use -ErrorAction Stop in order to catch a non-terminating error. The problem with that method is that I don't want my code in the try script block to actually stop. I want it to continue but handle the non-terminating errors. I would also like for it to be silent. Is this possible? Maybe I'm going about this the wrong way.

    An example of a nonterminating error I would like to handle would be a access denied error to keyword folders from Get-Childitem. Here is a sample.

    $getPST = Get-ChildItem C:\ -Recurse -File -Filter "*.PST" 
    $pstSize = @()
    Foreach ($pst in $getPST)
    {
         If((Get-Acl $pst.FullName).Owner -like "*$ENV:USERNAME")
         {
             $pstSum = $pst | Measure-Object -Property Length -Sum      
             $size = "{0:N2}" -f ($pstSum.Sum / 1Kb)
             $pstSize += $size
         }
    }
    $totalSize = "{0:N2}" -f (($pstSize | Measure-Object -Sum).Sum / 1Kb)
    
  • HiTech
    HiTech over 10 years
    Thank's for the reply. I'm trying to handle the Get-ChildItems that are outside of my Foreach loop. So if i put a ErrorAction Stop. It will stop on the first error and NOT contiune.
  • HiTech
    HiTech over 10 years
    I mentioned what I'm trying to do in my orignal post. I would like to handle each 'Access Denied' error coming from Get-Childitem. Depending on the filename, i will handle it differently.
  • mjolinor
    mjolinor over 10 years
    You can't interrupt the get-childitem. You can set the Error Action to Silently Continue, and use Error Variable to collect the errors and handle them after it finishes.
  • HiTech
    HiTech over 10 years
    That's what i figured. Thank you for clarifying.
  • HiTech
    HiTech over 10 years
    The code block in your post is not the answer to my question but your last comment was what i was looking for. So i will mark this as the answer.