How to Add Comments in PowerShell Scripts?

Adding comments in PowerShell scripts is a great way to document your code and make it more readable for others (and yourself) to understand what your script is doing. Comments can be used to explain the purpose of a script, the different parameters available, or to provide additional information about a script’s execution. Comments can also be used to provide instructions for other users who may need to modify or troubleshoot the script. In this article, we will discuss how to add comments in PowerShell scripts and how to use them effectively.

How to comment in PowerShell?

Comments are an essential part of writing PowerShell scripts. To add a comment in PowerShell, use the # symbol followed by your comment text. Anything on the same line after the “#” symbol will be ignored by the interpreter and will not be executed. Here is the PowerShell comments example:

# This is a comment
Write-Host "Hello, World!" # This is also a comment

In the above example, “This is a comment” and “This is also a comment” will not be executed, as they are preceded by the “#” symbol. In other words, comments can also be used to temporarily disable lines of code in a script. This can be useful if you want to troubleshoot and test a script without running certain commands. To do this, just add a # symbol before the command, which will cause the command to be ignored by the PowerShell interpreter. For example, if you wanted to skip a command, you could add the following comment:

# Get-Service -Name MyService # Skip this command.

Comments can be used to explain what a particular line of code does, why it is being used, and how it works. They can also be used to provide instructions or warnings to other users who may be reading or modifying the script.

Comment Block or Multiline Comment in PowerShell

PowerShell also supports multi-line comments. To add a multi-line comment, you must use the <# and #> tags to mark the start and end of the comment. Any text between the tags is treated as a comment, and the tags themselves are not executed as part of the script. This is useful for longer comments, or for comments that span multiple lines of code.

<#
    This is a multi-line comment that can be used to provide more detailed information about a script or function.
    For example, you can use it to explain the purpose of the script, the parameters it accepts, and how it should be used.
#>

Please keep in mind that all the above examples are for comments, PowerShell interpreter will not execute any of the lines that are commented with the above examples.

Add comments to parameters in PowerShell

You can add comments to parameters by using the “#” symbol followed by your comment text. For example, if you have a script with a parameter named “FilePath” and you want to add a comment to explain what the parameter does, you would add the following line at the top of your script:

Function Get-FileSize
{
    param(
        # The path to the file to get size
        [parameter(Mandatory=$True)]
        [string]
        $FilePath
    )
    # Get file size in bytes
    $FileSize = (Get-Item -Path $FilePath).Length

    Return [math]::Round($FileSize/1KB,2)
}

#Call the function to get file size
Get-FileSize -FilePath "C:\temp\Applog.zip"

Insert Function template with comments in PowerShell

Comments allow you to document your code and provide helpful information to other users who may be reading or modifying your scripts. Here is how the function template with Comments block looks like in PowerShell. This example also shows how to add comments to parameters.

<#
.Synopsis
   Add Prefix to All files
.DESCRIPTION
   Rename all files in a directory by adding a given prefix to each file name
.EXAMPLE
   Add-PrefixToAllFiles -FolderPath "C:\temp\Docs" -Prefix "Invoice"
.EXAMPLE
   Add-PrefixToAllFiles "C:\temp\Docs" "Invoice"
#>
Function Add-PrefixToAllFiles
{
    [CmdletBinding()]
    Param
    (
        # The path to the Folder where the files are located
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]
        $FolderPath,

        # The prefix to be added to the file names        
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]        
        [string]
        $Prefix
    )

    Begin
    {
        # print a message
        Write-Host "Starting renaming of All files in $FolderPath..." -f yellow

    }
    Process
    {
        # Get all files in the specified Folder
        $Files = Get-ChildItem -Path $FolderPath -File

        # Loop through each file and rename it
        ForEach ($File in $Files) {
            $NewName = "$Prefix" + "_" + $File.Name
            Rename-Item -Path $File.FullName -NewName $NewName
        }
    }
    End
    {
        # Confirmation message
        Write-Host "All files in $FolderPath have been renamed with the prefix $Prefix." -f Green
    }
}

#Call the function to rename all files in a directory
Add-PrefixToAllFiles -FolderPath "C:\temp\Docs" -Prefix "Invoice"

In this example, the comments at the top of the script describe the purpose of the script and the parameters that it accepts. The comments inside the script explain the purpose of each block of code. This helps to make the script more readable and easier to understand for others who may need to use or modify it in the future.

You can insert this function block with comments from snippets in PowerShell ISE.

powershell comments

Best Practices for using comments in PowerShell

When creating comments, it’s important to keep them clear and concise. Avoid using overly complex language or acronyms that may not be familiar to others. It’s also a good idea to include comments at the beginning of your script to explain what it does and how it works. This will make it easier for others to understand and use your script.

Another good practice is to use comments to explain any complex or tricky code. This will help others understand what is happening and make it easier to maintain your script. It is also best practice to use comments to include information such as the author, date created, any known issues or limitations of your script. Additionally, it is a good idea to use comments to break up and organize your script into logical sections, making it easier to understand and navigate.

Avoid using unnecessary words or phrases, as this can make the comment difficult to read. Additionally, it is important to be consistent with your comments. For example, if you are using a particular style of commenting, then make sure to use that same style throughout the script. Finally, make sure to use meaningful comments that provide helpful information to other users who may be reading or modifying the script. Don’t forget to keep them aligned, and make it easy to read.

Conclusion

In conclusion, adding comments to your PowerShell scripts is an important part of writing code, that helps for keeping your code organized, readable, and maintainable. They provide explanations, notes, and documentation that make it easier for others to understand and use your script. By keeping your comments clear, concise, and well-organized, you can ensure that your script is easy to understand, maintain, and troubleshoot. By following these tips, you can ensure that your comments are effective and helpful.


Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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