PowerShell Commenting Best Practices

There are a number of PowerShell “best practices” out there, and the one that I think that is most misunderstood is:

 

Avoid Excessive Comments (over-commenting)

 

The theory (probably correctly) says that your code should be self-documenting/self-explanatory, and should include things like:

  • Using meaningful variable names (eg: use $username instead of $u, so you don’t have to later figure out what $u is)
  • Not writing comments for well-known cmdlet functions that are obvious in their purpose (eg: everyone know what get-service does, so why comment on it?)
  • Not writing comments for well-known operators/comparisons that are obvious in their purpose (eg: if ($username -ne $null) {… )
  • Not writing massive “one-liners” that no-one can decipher at a glance
  • Not using cmdlet aliases

In this way, you end up with code that is easily readable and understandable, and not padded out with “filler”, in the form of comments.

Again, I 100% agree with the above.

 

But.

 

When it comes to writing comments in your PowerShell scripts, the single-most important rule should be:

 

Write (and comment) for your intended audience.

 

Above all else, your script needs to be supportable when you’re not around. I cannot stress this enough.

In my case, most of my scripts are handed-over to people who are not experts in either PowerShell or coding (much like myself), and long after I’ve gone, these scripts will still need to be maintained and modified by those same people – some of whom may only have the faintest grasp of how to write/modify/use PowerShell. ┬áMaking their future task easier is your responsibility, right now.

So – yes, the scripts I post here are *heavily* commented to the point of over-commenting – but it’s intentional, with the goal to make my scripts as understandable and supportable by as many people as possible.

 

2 Comments PowerShell Commenting Best Practices

  1. Johannes

    This! Exactly this.

    Pretty much all of my PS Code will be used/maintained by people without the necessary deeper PS knowlegde.

    So yes there will be over-commenting but at least I don’t need to field support calls for simple stuff.

    Reply

Leave a Reply to chriskenis Cancel reply

Your email address will not be published. Required fields are marked *