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.

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.

Did I mention that registration for the PowerShell & DevOps Global Summit 2018 is now open? I’ll be presenting there as well as Thomas Rayner who is referenced in this blog article.

µ

3 Comments

  1. absoblogginlutely

    Thats a nice tip. Obviously works in VSCode too.

    Reply
    • absoblogginlutely

      I also added this as a snippet to vscode, so entering demo and then tab will enter that text for me. Much easier to remember and quickly add to scripts

      {
      “UseDemoTrap”: {
      “prefix”: “demo”,
      “body”: [
      “#region PreventscriptfromrunningwithF5”,
      “throw ‘You’re not supposed to hit f5”,
      “#endregion”
      ],
      “description”: “Prevent Script from running when pressing F5”
      }
      }

      Reply

Leave a Reply

%d bloggers like this: