PowerShell Comments

When you want to help others by providing the information about a code, then you must use the comments in that code.

Just like other programming or scripting languages, you can give the comments in a PowerShell for the documentation purpose.

In PowerShell, there are two types of comments:

  • Single-line Comment
  • Multiple-line comment or comment block

Single line comment

Single line comments are those comments in which you can type a hash symbol # at the beginning of each line. Everything to the right of the hash symbol will be ignored. If you write the multiple lines in a script, you had to use the hash # symbol at the starting of each line.

Syntax of Single line comment

The following are the two syntaxes for the single-line comment:

Syntax1:

  1. <Any Command or statement> # <Any comment>  

Syntax2:

  1. # <Any comment>   
  2. <Any Command or statement>  

Examples

Example1: This example displays how to use the comment at the end of a line

  1. PS C:\> get-childitem #this command displays the child items of the C: drive  

Example2: This example displays how to use the comment before the code and at the end of any statement.

PS C:\> #This code is used to print the even numbers from 1 to 10  

PS C:\> for($i = 1; $i -le 10; $i++) # This loop statement initialize variable from 1  

and increment upto 10.  

>> {  

>> $x=$i%2  

>> if($x -eq 0) # The if condition checks that the value of variable x is equalt to   

0, if yes then execute if body  

>> {  

>> echo $i # This statement prints the number which is divisibel by 2  

>> }  

>> }

Output:

2
4
6
8
10

Multiple line comment

With PowerShell 2.0 or above, multiple line comments or block comments have been introduced. To comment the multiple lines, put the <# symbol at the beginning of the first line and #> symbol at the end of the last line.

Syntax of multiple line comment

The following block displays the syntax of multiple line comment:

  1. <# Multiple line Comment………  
  2. ………  
  3. ………………..#>  
  4. Statement-1  
  5. Statement-2  
  6. Statement-N  

Example: The following example describes how to use the multiple line comment in code.

PS C:\> <# This code is used to print the  

>> factorial of a given number#>  

PS C:\> $a=5  

PS C:\> $fact=1  

PS C:\> for ($i=$a;$i -ge 1;$i--)  

>> {  

>> $fact=$fact * $i;  

>> }

Type the following command to display the output of above example:

PS C:\> $fact
120

Posted

in

by

Tags:

Comments

Leave a Reply

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