0

I have some lengthy scripts which involve dynamic processes that I'd like to guarantee close, e.g.,

  • start-transcript --> stop-transcript
  • [io.StreamReader]$file --> $file.close(); $file.dispose()
  • setting an environment variable for the script duration.

I think the environment variable can be set to process scope to enforce it to be temporary and annulled at the culmination of the script; however, for the other two, it would be very convenient to have something like a finally block that would correctly end these processes even in the event of an error or manual cancellation.

The finally block is perfect for smaller scripts, but in an entire module or longer script, it looks inelegant to set the entire module/script in a try block just to squeeze in a few lines of a finally block at the end.

Is there a way to achieve the guaranteed execution of a finally block without needing to use a finally block and by association a try block?

PS(5.1.19041)

Blaisem
  • 557
  • 8
  • 17
  • Begin, process and end blocks might help you https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_methods?view=powershell-7.2 – LightningWar Nov 23 '21 at 21:53
  • LightningWar beat me to it! The end block is what you're after – Abraham Zinala Nov 23 '21 at 21:58
  • 3
    IIRC the end block does not run when ctrl+c is invoked where a finally would. – Doug Maurer Nov 23 '21 at 22:14
  • @DougMaurer, that's good to know! – Abraham Zinala Nov 23 '21 at 22:24
  • That’s strictly if I recall correctly lol. – Doug Maurer Nov 23 '21 at 22:37
  • That's a good point the End block is an alternative. Unfortunately, it requires a Begin and Process block, too. It'd be easier to just run try-finally blocks in that case, especially if it's true that cancelling the script circumvents the End block. – Blaisem Nov 23 '21 at 23:39
  • 2
    To add to the comment of @LightningWar, there's currently RFC's under review for PowerShell Core to add a cleanup function or `clean` block as a peer to `begin`, `process` and `end`. See [PR#9900](https://github.com/PowerShell/PowerShell/pull/9900) and [PR#15177](https://github.com/PowerShell/PowerShell/pull/15177) for further detail. – nimizen Nov 23 '21 at 23:49
  • 1
    See [this answer](https://stackoverflow.com/a/1789948/15339544) for an alternative to `try catch finally` and no, the end block of an advanced function does not apply if you CTRL+C. – Santiago Squarzon Nov 23 '21 at 23:55
  • @nimizen It seems to be attached to the begin process end blocks. Is it intended or "good practice" that all PowerShell scripts wrap their code in these blocks? It just seems unwieldy for longer scripts, especially when you are calling nested subscripts, and you only need to process once. – Blaisem Nov 24 '21 at 19:17

0 Answers0