Author Posts

February 22, 2018 at 9:31 pm

The below code does not work due to finally not being directly associated with try/catch

Is there a way to have the finally work when allying for pipeline input?

placing an empty Try/Catch inside of end works, but I'm not sure if it will fire as expected if process throws a terminating error, and I don't want to leave the session open when the function exits.

Begin {
  Try {
    # code to connect to import remote session
  } 
  catch {
    # error handeling
  }
}
Process {
  # do cooll stuff
}
end 
{
  finally
  { 
   # remove remote session
  }
}

February 22, 2018 at 11:39 pm

A correct begin, process, end, try , catch, finally structure should look like this I think.

    begin {
        try {
        } 
        catch {
            throw
        }
        finally {
            
        }
    }
    process {
        try {
            
        } 
        catch {
            throw
        }
        finally {
            
        }
    }
    end {
        try {
        } 
        catch {
            throw
        }
        finally {

        }
    }

So each block has its own error handling.

February 25, 2018 at 3:22 pm

But will the finally in end run if the catch in process throws?

February 25, 2018 at 5:37 pm

Hmmm .... yes and no. The Finally blocks always run, regardless of whether the Try block encounters a terminating error. But they are not related. If you need for whatever reason a relation between the Try and Catch block of the Process part and the Finally block of the End part you will have to create it by yourself.

You might reread the help for this concept:

Get-Help about_try_catch_finally

😉

February 26, 2018 at 9:04 pm

Finally blocks only run when the throw is in a catch, and only if they are in the same scope
looks like my best option is to try/catch to turn termination into non-terminating so end still runs.

February 26, 2018 at 10:43 pm

Well, the documentation tells us something else:

About Try Catch Finally

The finally block ALWAYS run. If you don't believe me or the documentation you should do your own research. 😉

But yes – the Finally block hast to follow directly the catch block. But if you change the termination into non-terminating the catch block will not run – never – only if a terminating error occurs anyway.