Have you ever come across a script on the Internet that looks exactly like what you want but you can’t understand it? It has no comments, no help content, and you can’t follow the code? This situation is all too common. Don’t be that script author.
Write your code so the next person can understand your code. Writing clear, concise code also means you’ll end up helping yourself. More often than not it seems that after not touching a piece of code for six months or more, you are the “next person” who ends up having to come back through and clean up what you previously wrote. By taking the following precautions, you’ll be able to save yourself and the next coder countless hours on your projects.
Give Your Variables Meaningful Names
Variable names should be meaningful. When you go back through your code, you shouldn’t be wondering what $x is or how you are supposed to use it. You should be able to pick up exactly what it’s supposed to do the first time through. With PowerShell, there’s no practical limit to how long your variable names should be, so feel free to be as descriptive as possible.
Notice the $r variable
Look up to see that $r is the foreach loop iterator variable part of the $x collection
Continue to follow where $x came from to find that it’s file contents from some file pointing to $t
Then finally see that $t points to servers.txt
You could have saved four steps just by changing the $r variable name to what it actually is ($serverName).
Tip Source: https://twitter.com/lh_aranda
Further Learning
String Substitution
When working with strings, you sometimes need to insert variable values inside of other strings. One way that is a bit clearer than other methods is called string formatting using the -f string operator. The -f string operator acts as a placeholder allowing you to insert values inside of other strings.
Let’s say you have a script that provisions your company’s servers. You’re using the script to create a standardized naming convention with server names that start with the department name they’re being used for like HR-SRV, ACCT-SRV, and ENG-SRV.
Now you have a placeholder ({0}) representing the place where the value of $dept will be. Most people consider string formatting a bit more clear especially when it comes to inserting many different variables inside of a single string.
Tip Source: https://twitter.com/harringg
Further Learning
Keep Aliases to the Console Only, Not in Scripts
- 1.
Lack of clarity – You’re adding another layer of complexity by using a reference to a command rather than calling a command on its own.
- 2.
Inconsistent syntax – You are free to use aliases or the actual command name whenever you like. As humans, we are terribly inconsistent which probably means you’re going to use the command alias sometimes and the actual command other times.
- 3.
Aliases can vary by system – If you create a custom alias on your computer and then share that script with others, the script will break. You are including an unnecessary dependency in your script you will then have to manage.
- 4.
Some aliases are not cross-platform – ls, for example, is an alias for the Get-ChildItem cmdlet on Windows, but ls is an actual Bash command on Linux. Invoking ls on Windows and Linux invoke different commands altogether.
Don’t use aliases in your code. Aliases are fine as shortcuts in your console session but keep them there. Don’t be tempted to use aliases in scripts or modules. Your code will be simpler and clearer.
Tip Source: https://twitter.com/TheTomLilly
Further Learning
Put Functions in Alphabetical Order in a Module
If you have a module file (PSM1) with many different functions, consider defining them in alphabetical order. If you have a module with dozens of functions, you should make it as easy as possible to find a function. One way to do that is through alphabetical ordering.
Out of order module function listing in VS Code
Tip Source: https://twitter.com/raychatt
Explain Regular Expressions with Comments
There are times when you need to match and parse strings in PowerShell and simple pattern matching just won’t cut it. You must use regular expressions. If you have to write a complicated regular expression in a script, be sure to provide a comment above it indicating exactly what kind of string it matches. There aren’t many regular expression gurus out there that can read a regex string like reading command name. Make the code as easy to understand as possible.
Include some example strings the regex expression matches too. Examples are always appreciated.
This is a simple tip but one that will help bring more clarity to those regular expressions.
Tip Source: https://twitter.com/guyrleech
Write Comment-Based Help
Always include comment-based help especially if you’re sharing scripts with other people. Comment-based help is the easiest kind of help to write. It shows up when a user runs Get-Help and acts as comments in the code too. Comment-based help should be standard across all production-ready scripts you write.
Once this function is loaded into your session, you can then use Get-Help -Name Get-ConfigurationFile to see all of the help content without even going into the code.
Further Learning
Weigh the Difference Between Performance and Readability
When writing code, you’re forced to weigh decisions based on many factors. Two factors that sometimes collide are performance and readability. It’s important for code to accomplish a task as quickly as possible but not at the cost of readability. Even though a computer doesn’t need white space, comments and long command names doesn’t mean humans don’t.
There are many instances where you can increase performance in expense of readability, but let’s narrow down an example to a simple one: adding items to a collection.
You can add items to a collection many different ways in PowerShell. Some ways are simple and succinct yet others are faster by getting you into creating your own .NET objects and calling methods.
However, this simple method is actually tearing down that collection in the background and creating a new one. PowerShell is so fast though, you wouldn’t notice anyway for even collections with a few thousand items in it.
This method is clearly more obtuse than the earlier example, but it’s faster especially with large collections.
Don’t use the fastest method all of the time if it’s going to affect readability. If you don’t ever intend to process more than a few thousand items in the collection, just use the += operator; otherwise, use an array list.
Further Learning
Consider Trade-offs Between Performance and Readability