How to Add Comments in PowerShell?

If you want to write industry-standard PowerShell scripts, you should know how to add comments in PowerShell. Let me explain this in detail with examples.

To add comments in PowerShell, you can use the hash symbol (#). Any text following the # on the same line will be treated as a comment and ignored during execution. For example:

# This is a single-line comment
Write-Output "Welcome to, PowerShell World!"

This method is useful for adding brief explanations or notes within your scripts. For more detailed comments, you can use comment blocks by enclosing the text in <# and #>.

Why Use Comments in PowerShell?

In a PowerShell script, comments are very important for the following reasons:

  1. Documentation: Comments serve as in-line documentation, explaining what the code does.
  2. Debugging: They help in isolating parts of the code during debugging.
  3. Collaboration: When working in teams, comments help others understand your logic and reasoning.
  4. Maintenance: They make it easier to update and maintain the code in the future.

Types of Comments in PowerShell

PowerShell supports two types of comments:

  1. Single-line comments
  2. Multi-line comments

Single-line Comments in PowerShell

Single-line comments in PowerShell start with the # symbol. Everything after the # on that line is considered a comment and is ignored by the PowerShell interpreter. These are typically used for short explanations or notes.

Example

Here is an example of how to add single-line comments in PowerShell.

# This script calculates the sales tax for New York
$price = 100
$taxRate = 0.08875
$tax = $price * $taxRate
$total = $price + $tax

Write-Output "Total price including tax: $total"

In the above example, the comment explains what the script does. The # symbol indicates that the line is a comment.

You can see the output also in the screenshot below:

Add Comments in PowerShell

Check out How to Restart a Computer Using PowerShell?

Multi-line Comments in PowerShell

Multi-line comments are used for longer explanations or to comment out blocks of code. They start with <# and end with #>.

Example

Let me show you another example of using multiple-line comments in PowerShell.

<#
This script calculates the total sales for New York
and Los Angeles. It then compares the sales figures
to determine which city has higher sales.
#>
$city1 = "New York"
$sales1 = 150000
$city2 = "Los Angeles"
$sales2 = 175000

if ($sales1 -gt $sales2) {
    Write-Output "$city1 has higher sales."
} else {
    Write-Output "$city2 has higher sales."
}

In this example, the multi-line comment provides a detailed explanation of the script’s purpose, making it easier for others to understand it.

Check out PowerShell ForEach-Object vs ForEach

Comment-Based Help in PowerShell

PowerShell also supports comment-based help, which is a way to document your scripts and functions. This type of comment includes special keywords that describe the purpose, parameters, and examples of your script or function. Comment-based help starts with <# and ends with #>, similar to multi-line comments.

Let me show you an example.

Example

<#
.SYNOPSIS
    This script calculates the total sales for a given city.
.DESCRIPTION
    This script takes a city name and sales figure as input,
    and then outputs the total sales for that city.
.PARAMETER City
    The name of the city.
.PARAMETER Sales
    The sales figure for the city.
.EXAMPLE
    .\Calculate-Sales.ps1 -City "Chicago" -Sales 200000
#>
param (
    [string]$City,
    [int]$Sales
)

Write-Output "Total sales for $City: $Sales"

In this example, the comment-based help provides detailed information about the script, including its synopsis, description, parameters, and an example of how to use it. This information can be accessed using the Get-Help cmdlet.

Get-Help .\Calculate-Sales.ps1

Best Practices for Using Comments

To make the most out of comments in your PowerShell scripts, follow these best practices:

  1. Be Clear and Concise: Comments should be easy to understand. Avoid writing overly complex or lengthy comments.
  2. Stay Relevant: Only comment on what is necessary. Avoid stating the obvious.
  3. Keep It Updated: Ensure your comments are updated as the code changes. Outdated comments can be misleading.
  4. Use Comment-Based Help for Functions and Scripts: This makes your scripts more user-friendly and easier to understand.
  5. Avoid Commenting Out Large Blocks of Code: Instead, use version control systems like Git to manage different versions of your code.

Check out PowerShell ForEach-Object

PowerShell Comment Examples

Now, let me show you a few advanced examples of how to use comments in PowerShell.

Example 1: Comment Conditional Statements

Here is an example of how to add comments in conditional statements in PowerShell.

$city = "San Francisco"
$sales = 120000

# Check if sales are greater than 100,000
if ($sales -gt 100000) {
    Write-Output "Sales in $city are above target."
} else {
    Write-Output "Sales in $city are below target."
}

In this example, a comment is used to explain the purpose of the if statement.

Example 2: Comment in Loops

Let me show you another example, where I have explained how to add comments in loops in PowerShell.

$cities = @("Chicago", "Houston", "Phoenix")
$sales = @(200000, 180000, 160000)

# Loop through each city and display its sales
for ($i = 0; $i -lt $cities.Length; $i++) {
    Write-Output "Total sales for $($cities[$i]): $($sales[$i])"
}

Here, a comment is used to explain the purpose of the for loop.

Example 3: Using Comment-Based Help in Functions

Here is another example of comment-based help in PowerShell.

function Get-SalesReport {
    <#
    .SYNOPSIS
        Generates a sales report for a given city.
    .DESCRIPTION
        This function takes a city name and sales figure as input,
        and then outputs a formatted sales report for that city.
    .PARAMETER City
        The name of the city.
    .PARAMETER Sales
        The sales figure for the city.
    .EXAMPLE
        Get-SalesReport -City "Dallas" -Sales 250000
    #>
    param (
        [string]$City,
        [int]$Sales
    )

    Write-Output "Sales Report for $City"
    Write-Output "===================="
    Write-Output "Total Sales: $Sales"
}

# Generate a sales report for Dallas
Get-SalesReport -City "Dallas" -Sales 250000

In this example, comment-based help is used to provide detailed information about the Get-SalesReport function.

Conclusion

I hope that now you know how to add comments in PowerShell using the above examples. We discussed single-line comments and multi-line comments in PowerShell.

Whether you are writing a simple script or a complex module in PowerShell, always remember to include comments to explain your code.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.