Toughest Event Yet – 2012 PowerShell Scripting Games Beginner Event #3

The details of the event scenario and the design points for Beginner Event #3 of the 2012 PowerShell Scripting Games can be found on the “Hey, Scripting Guys! Blog”.

This was the toughest event out of the first three for me. I spent a lot of time researching how to check permissions because part of the first design point stated: “If you do not have permission off the root, create the nested folders where you have permissions”. This was clarified in the comments section later during the day and I was able to move on. Check the comments section of the event scenario’s often since there may be additional information posted in them that’s very useful.

I also spent a lot of time trying to figure out why try-catch wasn’t catching my errors since another one of the design points stated: “Your script should not generate errors (that are ignored)”. After a lot of research, I finally figured out that try-catch only catches terminating errors and I set the ErrorActionPreference to Stop for the entire script to put that problem to rest. I saw a tweet later that day from Jeff Hicks (@JeffHicks) about a new blog article of his titled “Try and Catch Me If You Can” that covers this exact problem.

Here’s the script I submitted. I also included comments in my submission. See my script on the PowerShell Code Repository site if your interested in seeing the comments. I try to keep my code as short and simple as possible while still meeting all the requirements.

It starts out by defining two parameters and setting default values that meet the requirements of the scenario. Then it sets the ErrorActionPreference to Stop for the entire script to keep it from having any unhandled errors. Then there’s the Try block. I really like using the If statement with the -not so if the first statement is true, the second one doesn’t execute and vise-versa. The pathType parameter checks for a container (directory) because if event3 was a file with no extension, it would return true without this option. If the path doesn’t exist, the directories are created. The Get-Process line is fairly generic except for the -Force parameter which will overwrite the file even if it is set to read only. Then there’s the catch block which will tell you why the command failed if there’s an error.

View my entry for this event on the PowerShell Code Repository site.


Leave a Reply

%d bloggers like this: