Better document your PowerShell code and provide comment-based help
Last Update: Nov 19, 2024 | Published: Jul 15, 2024
In this guide, you will learn about using PowerShell comments to help you better document your code and provide comment-based help capabilities for your PowerShell functions. By the end of this guide, you will be proficient and immediately effective at creating PowerShell comments to enhance readability and create documentation for your PowerShell scripts. Ready? Let’s get started!
Have you ever tried to use a product that didn’t come with a user manual? Not only is it frustrating to stumble your way through using the product, but not having the manual on its use can lead to undesired results. You could try to go behind the scenes to figure it out, but without some behind-the-scenes commentary, you may find yourself lost.
PowerShell comments are behind-the-scenes commentary. Not only do they serve as a sort of manual for your script, but comments can help you, the script creator, remember specific reasoning for doing things a certain way in your code. Comments are documentation.
It is important to remember that as you get started with PowerShell comments, be clear and concise. Professionals, novices, or you yourself may read the comments! However, using comments is better than making no comments at all. You may ask yourself, “How do PowerShell comments help enhance scripts? Below are the key reasons for PowerShell comments.
A PowerShell comments will always contain a `#` for single line comment or `<#…#>` for multi-line comment. These comment blocks are ignored during script execution.
Now that you have some baseline understanding of why ==PowerShell comments== are good to have, let’s dive into some examples in the sections below.
The most basic and often used type of ==PowerShell comment== is the single-line or inline comment technique. This type of comment is often a simple explanatory note or annotation within your code.
To create a ==single-line comment== in PowerShell, you use the #, or hashtag symbol. Whatever you type following the # on that line is a comment. Here’s an example below:
# This is a single-line comment.
Here’s another example, but this time as an inline comment:
Get-Help Get-Process -Online # Show me the online help for Get-Process cmdlet
Be careful with inline comments as sometimes they can be harder to read as they scroll off the right side of your window. We’ll go over that more later in this guide. Now that you understand how ==single-line comments== in PowerShell work, let’s go into the next section!
When you need to add detailed descriptions where a single line will not do, the multi-line comment technique allows you to create a comment block within your code.
To create a multi-line comment in PowerShell, you place your comments between a set of angle bracket and hashtag symbols (<# and #>). Here’s an example below:
<#
Multi-line comment or comment block example.
Everything between the angle bracket and hashtag
symbols are comments. Note how each line was
tabbed over in the block. More on this later ;-)!
#>
foreach ($item in $itemList) {
# Action code here
}
Now that you understand how multi-line comments in PowerShell work, let’s go onto some more advanced topics in the next sections!
Beyond single-line and multi-line comments in PowerShell is comment-based help. With this technique, you can add help documentation to PowerShell functions and scripts. Using comment-based help is a sign that you are a professional PowerShell scripter.
Using the previous multi-line example, there are several keywords that you can add within a multi-line comment block to enhance the documentation of your script or function. Here’s a basic example:
function Get-Greeting {
<#
.SYNOPSIS
This function returns a greeting message.
.DESCRIPTION
The Get-Greeting function generates a greeting message based on the current time of day.
It provides a personalized greeting if a name is supplied as a parameter.
.PARAMETER Name
The name of the person to greet. If no name is provided, it defaults to 'Guest'.
.EXAMPLE
PS C:\> Get-Greeting -Name "Alice"
Good morning, Alice!
.EXAMPLE
PS C:\> Get-Greeting
Good morning, Guest!
.NOTES
Author: Your Name
Date: Today's Date
Version: 1.0
.LINK
https://docs.microsoft.com/en-us/powershell/scripting/samples/sample-scripts-for-admin
#>
param (
[string]$Name = "Guest"
)
$hour = (Get-Date).Hour
if ($hour -lt 12) {
$greeting = "Good morning"
} elseif ($hour -lt 18) {
$greeting = "Good afternoon"
} else {
$greeting = "Good evening"
}
"$greeting, $Name!"
}
# To see the help, use:
# Get-Help Get-Greeting -Full
How did these comments enhance your function? Glad you asked! Here’s a real-world example. Let’s use Get-Help to figure out how to use your function:
Get-Help Get-Greeting -Full
Let’s say another user who has no clue what Get-Greeting does and wants to read your documentation. Again, the user could run the following code:
Get-Help Get-Greeting -Detailed
You can find more examples of comment-based help with more detailed information on Microsoft’s website.
Recall that in previous sections, everything after the hashtag # symbol is treated as a comment. That means adding at # before a line of code instantly turns that line into a comment and PowerShell will ignore it on script execution. This is useful when troubleshooting, debugging, and making code changes to scripts. Here are a couple of examples using single-line and multi-line techniques.
In the example below, you use a single line comment because you do not want to pipe the objects from Get-Process to the next cmdlet in the pipeline:
Get-Process | # Select-Object -Property Name, PID
Now, in this next example, you use a multi-line comment to exclude a block of code within a function from executing:
function Test-Switch {
param (
[string]$InputValue
)
# This switch statement is active
switch ($InputValue) {
"Case1" { "You selected Case1" }
"Case2" { "You selected Case2" }
default { "Unknown case" }
}
# This switch statement is commented out
# switch ($InputValue) {
# "CaseA" { "You selected CaseA" }
# "CaseB" { "You selected CaseB" }
# default { "Unknown case in the commented out switch" }
# }
}
# Example usage
Test-Switch -InputValue "Case1"
Notice how each line of code has a # preceding it. You accomplish the same goal by using multi-line commenting:
function Test-Switch {
==param== (
[string]$InputValue
)
# This switch statement is active
switch ($InputValue) {
"Case1" { "You selected Case1" }
"Case2" { "You selected Case2" }
default { "Unknown case" }
}
<# This switch statement is commented out using multi-line comment block
switch ($InputValue) {
"CaseA" { "You selected CaseA" }
"CaseB" { "You selected CaseB" }
default { "Unknown case in the commented out switch" }
}#>
}
# Example usage
Test-Switch -InputValue "Case1"
The reason you would use a multi-line comment technique here would be to allow one to collapse the comments in a script editor (like Visual Studio Code) to help readability. Be careful though, as placing the symbols at the wrong point can break your code!
In PowerShell, you can use region tags to organize and comment on your script into sections or regions. This makes it easier to read, navigate, and manage your code, especially in longer scripts. You create regions in PowerShell using the #region and #endregion tags.
Here’s how you can leverage region tags in PowerShell:
#region Variables
# Here you define all your variables
$var1 = "Value1"
$var2 = "Value2"
#endregion
#region Functions
# Here you define all your functions
function Get-Greeting {
param ($name)
return "Hello, $name!"
}
#endregion
#region Main Script
# Here is the main logic of your script
$name = "World"
Write-Output (Get-Greeting -name $name)
#endregion
In editors that support region folding (e.g., Visual Studio Code, PowerShell ISE), you can collapse or expand these regions. This helps you to focus on the section(s) of a script you’re working on without being distracted by other sections.
You can also nest regions within each other for more granular organization.
#region Script Initialization
#region Load Modules
# Code to load necessary modules
Import-Module ModuleName
#endregion
#region Set Variables
# Code to set variables
$var1 = "Value1"
$var2 = "Value2"
#endregion
#endregion
#region Main Script
# Main script logic
Write-Output "This is the main script."
#endregion
Using region tags effectively can enhance the structure and readability of your PowerShell scripts.
Writing clear and concise comments in PowerShell is essential for maintaining readability and understanding of your scripts, especially for future maintenance and for other users who might need to read or change your code. Here are some guidelines for writing effective comments in PowerShell:
If you like keyboard shortcuts in VS Code, you can use the shortcut key CTRL+ / to insert the syntax (the hash symbol #) for a single-line comment.
For multi-line block comments, enclose the text between <# and #>.
Example:
<#
This is a multi-line block comment.
It can span multiple lines.
Use it for more detailed explanations or documentation.
#>
If you like keyboard shortcuts in VS Code, you can use the shortcut key CTRL+SHIFT+A to insert the syntax for a multi-line block comment.
Ensure your comments are specific to the code they are describing. Avoid generic comments that don’t add value.
Example:
# Calculate the total cost, including tax
$totalCost = $price * (1 + $taxRate)
Regularly update comments to reflect changes in the code. Outdated comments can be misleading.
Focus on explaining why certain decisions occurred rather than just describing what the code does. The code itself should be clear enough to understand the ‘what’.
Example:
# Using a loop to handle large data sets efficiently
foreach ($item in $largeDataSet) {
# Process each item
}
If a part of the code is complex or uses an advanced feature, add a comment to clarify its purpose and functionality.
Example:
# Use the pipeline to filter and sort the results
Get-Process | Where-Object { $_.CPU -gt 100 } | Sort-Object CPU -Descending
At the beginning of your script or function, include a header comment that describes the purpose, parameters, and usage.
Example:
<#
.SYNOPSIS
This script calculates the factorial of a number.
.DESCRIPTION
A detailed description of the script.
.PARAMETER Number
The number for which to calculate the factorial.
.EXAMPLE
PS C:\> .\Get-Factorial.ps1 -Number 5
.NOTES
Additional notes or information.
#>
Use a consistent style for comments throughout your script. This makes it easier to read and maintain.
PowerShell supports comment-based help. If you have ever run the ==get-help== cmdlet, you can use this feature to provide detailed documentation for your scripts and functions just like the built-in cmdlets have.
Example:
function Get-Factorial {
<#
.SYNOPSIS
Calculates the factorial of a number.
.DESCRIPTION
This function takes a number and returns its factorial.
.PARAMETER Number
The number for which to calculate the factorial.
.EXAMPLE
PS C:\> Get-Factorial -Number 5
.OUTPUTS
System.Int32
#>
param (
[Parameter(Mandatory=$true)]
[int]$Number
)
if ($Number -le 1) { return 1 }
return $Number * (Get-Factorial -Number ($Number - 1))
}
Comments can be as simple or as complex as you want to make them. By following the basic guidelines below, you’ll be well on your way to better document your code:
Following these guidelines helps you write clear, concise, and helpful comments in your PowerShell scripts.
In this guide, you’ve learned all there is to learn about using comments in PowerShell. Using this new PowerShell knowledge, you can show your level of scripting professionalism. Who knows? The next person troubleshooting your script might be you!
Now, get out there and comment on your PowerShell code!