hashtag

How to put single line and multiline or block comments in Windows PowerShell

This seems to be a topic not worth for a post, but there are people looking with google for that.

In PowerShell single line comments start with a hash symbol and everything to the right of the # will be treated as comment and ignored as scripting code.

# This is a comment

Comments in PowerShell spanning multiple lines came with PowerShell 2.0. They start with "<#" and end with "#>". They can be placed anywhere, except inside strings, and anything between them will be treated as a comment.

<# This is a block comment #> Write-Host "Cmdlet after a block comment"
<# Here starts a
   multi line comment
#>
Write-Host "Cmdlet after a multi-line comment"

But there is more about comments. They can be used from the Get-Help cmdlet when a help keyword is given. This is then called comment-based help. This has to appear in one of three locations when they are used for functions:

  • At the beginning of the function body.
  • At the end of the function body.
  • Before the Function keyword. There cannot be more than one blank line between the last line of the function help and the Function keyword.

When used for scripts, the comments can appear in one of the following two locations in the script:

  • At the beginning of the script file. Script help can be preceded in the script only by comments and blank lines.
  • At the end of the script file. However, if the script is signed, place Comment-based help at the beginning of the script file. The end of the script is occupied by the signature block.
  • If the first item in the script body (after the help) is a function declaration, there must be at least two blank lines between the end of the script help and the function declaration. Otherwise, the help is interpreted as being help for the function, not help for the script.

To find out more, use:

Get-Help about_comment