Begin, End, Try, Finally

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
  }
}

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 {

    }
}</pre>

So each block has its own error handling.

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

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
:wink:

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.

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. :wink:

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.