When you’ve got two geeks discussing PowerShell around the water cooler you’ll inevitably get disagreement on how best to solve a problem.
“No! An if/then statement would be much better to test that condition rather than switch statement” or “I’d write a function there instead of using that same code again. That’s so inefficient!”.
Writing code in whatever language you choose is going to always be open for interpretation. This is why I’ve seen the argument that coding can actually be considered art. Just like with a great Picasso piece, some people may love it and some people may hate it. It’s open for interpretation. However, what makes code different than a painting is that it has a function behind it. The code must perform some action after it’s completed rather than just look pretty.
In the book The Pragmatic Programmer (affiliate link), the author explains that not only does your code have to be efficient it also has just plain work. Being pragmatic is what a good Powershell scripter, web developer, iOS app developer, etc must strive for.
The key is not getting bogged down in the details so much so that the code must be perfect. I used to struggle with this a lot when I was doing a lot of web development. I had to make the code as fast as possible with the least amount of lines or it was a failure. What I failed to see was that the user would use that feature and be perfectly happy with something that’d be 100ms slower and take me 6 hours less time!
To write a good-enough PowerShell script you must start out with a few goals in mind (in order of importance).
- By the time the script is finished did it accomplish what I needed it to?
- Is it fast enough?
- Did you minimize (not necessarily eliminate) redundancy in the code?
- Is it readable to others (only if you’ll be sharing it)?
These are just a few rough guidelines to go by. My whole point in this post is to show you to try not to get bogged down into making your code mistake-free. You’re not writing fully featured software here; it’s a script. Sysadmins aren’t developers. Just write a script to help you out and be done with it.