PowerShell Comments Example

Adding Comments in PowerShell


In PowerShell, effective commenting is not just a best practice; it’s a skill for maintaining clean, understandable code, as it is in other coding languages. Comments serve as guides for developers, offering insights into code functionality, reasoning, and even temporary code disabling. In this article we’ll share the two primary types of adding comments in PowerShell: single-line comments and multi-line comments.

How to Add Comments in PowerShell

1. Single-Line PowerShell Comments: #

Single-line comments for annotating individual lines or sections of code start with a pound sign (#) and extends to the end of the line.

# This is a single-line comment in PowerShell 
$variable = "hi powershell pals" # Assigning a string to a variable
PowerShell Inline Comment Example

As displayed above, you can add the pound sign to anywhere in the line of code and it’ll continue the the rest of the line as comment characters. These in-line comments are good for quick annotations or clarifications within your script, aiding the readability for others reading your code.

2. Multi-Line PowerShell Comments: <#…#>

For more extensive comments spanning multiple lines in PowerShell, we can add <# and conclude with #> as shown below:

<#
This is a multi-line comment in PowerShell.

We can temporarily add comments at the start and end of areas of code to disable it.
This is useful for debugging and revising unfinished work. 
#>

function Invoke-DatabaseQuery {
    # Function logic for querying the database
    Write-Host "Executing database query..."
}

<# 
--------------------------------------------------------------------------------------
To temporarily disable the function for revision purposes, comment it out.
--------------------------------------------------------------------------------------
function Invoke-DatabaseSQLQuery {
    # Function logic for querying the database
    Write-Host "Executing database query..."
}
#>
PowerShell Multi Line Comment Example

Multi-line comments are great for more detailed documentation on functions, algorithms, or sections within the code. They’re also useful for quickly commenting out a section of the code during debugging code.

Overall, adding comments to your PowerShell code will It makes it easier for others (and our future selves) to comprehend more complex code segments.

Hope this quick guide was a good one and what you were after. Feel free to check out my PowerShell Tips & Tricks page for more random PowerShell guides like this one.


Leave a Reply

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