PowerShell – Multiline Comment

Multiline comment in PowerShell

Using <# #> Tags

Use the <# tag at the beginning of comments and the #> tag at the end of comments to create multiline comments in PowerShell scripts. All lines inside the comment block are part of the comments.

In programming, we use a comment block to provide explanations or details about the code. The comments are used to document the program so that every programmer/developer can easily understand it. Let’s use multiline comments in the example to understand how we can use them in code:

In the above example, a multiline comment block is added to the script starting with <# and ending with #> that describes the code to print the first ten digits from 0 to 9.

Note: Code that has been appropriately commented out is easy for developers and maintenance staff to understand.

We can comment on a single line using #. In PowerShell 2.0 or older versions, the only option to add multiple-line comments was to use the # at the beginning of every line that we didn’t want to be read by the PowerShell interpreter.

It means that if the code explanation has ten or more lines, we must put # ten times at the beginning of each line. Like this:

Isn’t it look tedious to write # in front of every line again and again? But it is beneficial to write single-line comments as follows.

Let’s re-write the example written in the previous section using a single-line comment.

Here, a single-line comment is used to explain the code. Note that syntax or expression will not be executed within the comment block. Let’s see an example below:

We have not received any output in the above code snippet because Get-Location is in the comment block. Why? It is because PowerShell skips the code section during execution whenever it encounters the # keywords or anything between <# #> keywords.

Using Shortcut Keys

Use shortcut keys to add multiline comments while writing PowerShell script in Visual Studio.

Suppose we want to comment above lines. For this, we will select the lines first, then press ALT + SHIFT + A. It will enclose the selected lines with <# #> as <# selected lines #>. See the following example.

That’s all about multiline comments in PowerShell.

Was this post helpful?

Leave a Reply

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