When it comes to variables and parameters, I’ve seen some strange, horrible things. there is only one thing more annoying than someone cycling through the alphabet for variables, and that’s reusing the same variable in the entire script. Even with proper error handling that’s just a recipe for disaster!
Use meaningful names
When creating variables, please use meaningful names. For example, if you’re retrieving all users in active directory, don’t call use $x to store the output in, but rather use something like $AllUsers.
The general recommendation is to use Pascal Case. For example, it’s easier to read $ThisVariableContainsAllUsers than $thisvariablecontainsallusers. Something with the human psyche just messes with you when you try to read the latter variable name.
Microsoft Naming Guidelines:
Place any user-defined variables at the top of the script where possible. Usually this is something you’d do near the end of your dev cycle. Reasoning behind this is simple, it avoids others to hunt for variables that might need to be changed.
Whilst there are no concise rules around this, so when you’re in doubt whether you should move a variable to the top, ask yourself: “Might I, or someone else running this script, need to change this variable in the future?”, and secondly “Will moving this to the top break anything?”
Avoid unnecessary data output and/or retrieval
It happens to the best of us, sometimes we read data multiple times from disk in a single script. Most of the times that happens when we’re adding on functionality later and forgot we already had it in memory. Other times we might just have too much blood in our caffeine…
Remember when you read from disk instead of using the memory, you’re incurring a file system write and read I/O action. This will slow down the execution of your script. Whilst most of the times this will not be noticeable (nano vs milliseconds), it is still recommended to keep track of what you have in memory, and reuse as much as possible.
Parameters can be divided up in to 2 distinctly different sorts: Static, and Dynamic parameters.
[CmdletBinding()] is a special little cookie, as it gives us access to more advanced functionality with our functions. You can learn more about it here:
HBoPS #1: Use a proper editor!
HBoPS #2: Error handling and you!
HBoPS #3: Avoid using Write-Host (and save puppies!)
HBoPS #4: Variables, Parameters, and Battlestar Galactica
HBoPS #5: Reduce, Reuse, Recycle
HBoPS #6: Handling Credentials