Safety to prevent entire script from running in the PowerShell ISE

I recently watched fellow Microsoft MVP Thomas Rayner present a session on regular expressions for the MVP Days virtual conference. Sometimes it's the little things that are the biggest takeaways for me when I'm watching others present. One thing that wasn't related to regular expressions that I noticed was Thomas's way of preventing his entire script from running if F5 was accidentally pressed instead of F8 in the PowerShell ISE (Integrated Scripting Environment). If you're not aware, F5 runs the entire script (the demo would be over) and F8 runs the current selection. If F8 is pressed without having anything selected, the current line is run.

The code that Thomas used at the top of his demonstration script generates a terminating error if the entire script is run.

1#region Come on man
2throw "You're not supposed to hit F5"


I've used Break in the past, but I've run into some scenarios where break didn't work since it's designed to break out of a loop. Once I ran into problems with Break, I started using Start-Sleep to effectively pause the script long enough for me to figure out what I'd done. Thomas's example of using Throw to generate a terminating error is better than either of those options though.

I'm totally going to steal (I mean borrow) Thomas's code and start using it in my demos when I present.

I posted this tip on Twitter during the virtual conference, but the problem is I won't be able to find that tweet later since it isn't indexed for easy searchability.


According to Thomas, there are videos of the sessions from the MVPDays virtual conference and the code from his session can be found in his Presentation-Files repository on GitHub.