Home > Back-end >  finally is skipped if the catch is triggered
finally is skipped if the catch is triggered

Time:10-25

this is PS 5.1

try {
    Send-MailMessage -to $EmailTo -Body $Body -Subject "$TodayDate Report" -From '[email protected]' -SmtpServer 'mail-relay' -port '25' -BodyAsHtml -ErrorAction Stop
}
Catch {
    Write-Warning "Unable to send email"
    & gam user $($EmailTo) sendemail html true to $($EmailTo) subject "$TodayDate Report"
}
finally {
       #final cleanup
    If (@($UsersResultsArray).count -gt 0) {
        remove-Item $UsersResultFileName -Force -ErrorAction SilentlyContinue
    }

    IF ($ArchiveOverFlowCount -gt 0) {
        remove-Item $ArchiveOverFilename -Force -ErrorAction SilentlyContinue
    }

    If ($ZeroCount -gt 0) {
        remove-item $ZeroArrayFileName -Force -ErrorAction SilentlyContinue
    }

    remove-Item $NumbersTableFilename -Force -ErrorAction SilentlyContinue
}

I have tried many combinations but if the try gets an error the catch works but the finally does not.

I have tried no finally and nothing happens after the catch.

No errors. I am not sure what is going on or why nothing happens after the catch?

If the Try does not get an error everything works fine.

I tested with a continue in the catch and whatever I do if the catch fires the finally does not.

CodePudding user response:

The documentation says:

The finally keyword is followed by a statement list that runs every time the script is run, even if the try statement ran without error or an error was caught in a catch statement.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.2

Now lets test:

try {
    get-item C:\nothing.there -ErrorAction:Stop
}
catch {
    write-error $_
}
finally {
    write-host "finally"
}

#Output:
Write-Error: Cannot find path 'C:\nothing.there' because it does not exist.
finally

So the catch caught the error and finally got executed.

try {
    get-item C:\Windows -ErrorAction:Stop
}
catch {
    write-error $_
}
finally {
    write-host "finally"
}

#Output:
    Directory: C:\

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          12/10/2022    22:29                Windows
finally

Once again finally got executed.

So back to your example, I think that the variables used in the IF statements, e.g. $UsersResultsArray, are empty or the variables that should contain paths like $UsersResultFileName.

To verify if the finally block runs, simply add write-host "finally" to that block and re-run the code, you will see "finally" printed on the screen.

Btw. to verify if the variable holds elements you do not need to count them, this is enough: IF ($UsersResultsArray){}.

  • Related