How to Add Comments to Your PowerShell Code and Scripts

Better document your PowerShell code and provide comment-based help

Last Update: Nov 19, 2024 | Published: Jul 15, 2024

PowerShell

SHARE ARTICLE

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.

Understanding comments in PowerShell

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.

Clarification and understanding

  • Explanation of Code: Comments allow you to explain what specific code snippets do, making it easier to understand complex scripts or concepts. Here’s an example
PowerShell comment - explanation of code
PowerShell comment – explanation of code (Image Credit Bill Kindle/Petri.com)
  • Annotations: Annotate the purposes of variables, functions, and logic to reinforce understanding. Here’s how to use the hash symbol syntax to comment text:
Annotations in PowerShell code
Annotations in PowerShell code (Image Credit Bill Kindle/Petri.com)

Debugging and troubleshooting

  • Temporary Changes – Comments enable you to disable code temporarily without deleting it, which is useful when debugging scripts.
Temporary changes to PowerShell code
Temporary changes to PowerShell code (Image Credit Bill Kindle/Petri.com)


  • Notes on Issues – Document known issues or areas of concern directly in the script.
Notes on issues in PowerShell code
Notes on issues in PowerShell code (Image Credit Bill Kindle/Petri.com)

Documentation

  • Script Overview – Provide a high-level overview of the script at the beginning, detailing the purpose and functionality.
Using a PowerShell comment to provide an overview of a script
Using a PowerShell comment to provide an overview of a script (Image Credit Bill Kindle/Petri.com)
  • Function Documentation – Use comments to document functions, including parameters and return values.
PowerShell Function documentation
PowerShell Function documentation (Image Credit Bill Kindle/Petri.com)

Learning and collaboration

  • Sharing Knowledge – Comments may help others who may read your script to understand your logic, making collaboration easier.
Sharing knowledge in PowerShell comments
Sharing knowledge in PowerShell comments (Image Credit Bill Kindle/Petri.com)
  • Reinforcing Concepts – Writing comments will force you to think through and explain your logic, reinforcing your understanding. Doing this before beginning a script is called pseudocode.

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.

Creating single-line comments

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!

Creating multi-line block comments

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!

Advanced commenting techniques

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 comments for documentation

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 
Advanced PowerShell commenting for documentation
Advanced PowerShell commenting for documentation (Image Credit Bill Kindle/Petri.com)

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 
Using the -detailed switch to get advanced documentation in PowerShell
Using the -detailed switch to get advanced documentation in PowerShell (Image Credit Bill Kindle/Petri.com)

You can find more examples of comment-based help with more detailed information on Microsoft’s website.

Using comments to disable code

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!

  • Leveraging comments for version control and change tracking.
  • Leveraging region tags to comment code into sections or regions.

Organize code with regions

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:

Basic syntax

  • Start a region: #region Description.
  • End a region: #endregion.

Example usage

#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

Detailed breakdown

  1. Starting a Region:
    1. An optional description follows the #region tag. This description helps to identify the purpose of the region.
    1. Example: #region variables show that the following code block is related to variable definitions.
  2. Ending a Region:
    1. The #endregion tag marks the end of the region.
    1. Example: #endregion placed after the variable definitions end the region started by #region variables.

Benefits of using region tags

  • Improved Readability: By logically grouping related sections of code, you make the script easier to read and understand.
  • Easier Navigation: Many editors, such as Visual Studio Code, allow you to collapse and expand these regions, making it easier to navigate through large scripts.
  • Maintenance: It simplifies code maintenance by clearly delineating different parts of the script.

Collapsing and expanding regions

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.

  • Collapsed View: Only the #region line with its description is visible.
  • Expanded View: The entire code block within the #region and #endregion tags is visible.

Example with nested regions

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.

Best practices for commenting in PowerShell

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:

1. Use single-line comments

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.

2. Use multi-line comments

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.

3. Be specific and relevant

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) 

4. Keep comments up to date

Regularly update comments to reflect changes in the code. Outdated comments can be misleading.

5. Use comments to explain ‘Why’ not ‘What’

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 

6. Comment on complex or non-obvious code

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 

7. Use descriptive header comments

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. 
#> 

8. Consistent comment style

Use a consistent style for comments throughout your script. This makes it easier to read and maintain.

9. Use comment-based help

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)) 

Follow basic guidelines to better document PowerShell code

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:

  • Use # for single-line comments and <# #> for multi-line block comments.
  • Be specific and relevant.

  • Explain why, not just what.

  • Keep comments up-to-date.

  • Comment on complex or non-obvious code.

  • Use descriptive header comments and comment-based help.

  • Maintain a consistent comment style.

Following these guidelines helps you write clear, concise, and helpful comments in your PowerShell scripts.

Show you level of scripting professionalism with PowerShell comments

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!

Table of contents

Table of contents

SHARE ARTICLE