Best Practice: It is recommended to avoid excessive comments (over-commenting).
Explanation:
The code should be enough self-explanatory so that no comments at all are needed. I would recommend to refactor the code instead of adding comment to the code logic.
For example, if you have block of code of 15 lines and you want to explain what does this block by adding comments, it would be better (instead of commenting) to create 3 methods of 5 lines with understandable name (Get-Header, Get-Title, Get-Body).
Commenting the code logic is usually considered an anti-pattern because it means that your code is not self-explanatory.
The following code is definitely “too much” commented and makes too difficult to read.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
######################## ##### Start Script ##### ######################## ########################################################### This script is used to receive the list of stopped services ########################################################### # The variable $services contains all services $services = Get-Service # Start of the Foreach loop foreach ($service in $services) { # We are checking if the service is stopped # Start of the If condition if ($service.Status -eq 'Stopped') { # If the service is stopped, we display the service $service } # End of the If condition } # End of the Foreach loop ######################## ##### End Script ####### ######################## |
You don’t need to explain that you are getting to retrieve the list of services before the cmdlet “Get-Service“, it is already self-explanatory.
Now, see the difference with that one, much clearer to read, extra comment have been removed:
1 2 3 4 5 6 7 8 9 |
$services = Get-Service foreach ($service in $services) { if ($service.Status -eq 'Stopped') { $service } } |
Important: Do not confuse with “Comment-Based Help (CBH)” which is useful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
function Get-Something { <# .SYNOPSIS Short description .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .PARAMETER ComputerName This parameter accepts one or several computers (array) .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES General notes .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> [CmdletBinding()] Param ( [String[]]$ComputerName ) } |