Well that's interesting. There seems to be something inside PSP that needs to get tripped or set but I don't know what it is. And that's probably a wrong assumption.
So I went through like six different scripts with various combinations of commands to come up with the following oddity.
If I have a script and it uses Undo, it'll fail every time no matter how many commands I have. And it doesn't seem limited to specific commands. However, if I make a selection before I run the script, the script executes perfectly and will continue to execute perfectly every time after that. It's like it requires an initial edit outside of a script for UndoLastCmd to work.
My first solution is to just hit CTRL + D before running your script. Ctrl + D does nothing since there are no active selections, and the script runs just fine after that.
If you want a scripting only option, that's where it gets annoying and ugly.
For a pure scripting solution you need a second script. This script will do two things. 1) Runs "SelectNone" and 2) Runs "RunScript" on the script you wanted to run.
Here is a quick video showing what I mean:
https://drive.google.com/a/trinitybible ... JzRUk/view