Monday, February 11, 2013

Powershell Best Practices: Commenting in Powershell. While optional, Its highly encouraged.

 This post is more of a “best Practice” then a “How To,” although, It does contain some how elements.  Commenting in any programming language is in important function, and even more so in Powershell due to the fluid nature of scripting.  While not officially defined, I like to think there are 4 types of comments:

Header: This includes the authors name, the creation / last modification date, and the purpose.  This is important as a script can be renamed a number of times, but you need to know what your published script does.  Some companies even mandate this set of comments as a way of tracking employs work.

# Author: John Doe
#Date Created: 1/1/2010
#Date Last Modified: 2/2/2012
#Purpous: Provide an example of commenting out a header

Explanation:  Code is confusing.  Very confusing.   When a large script is written, it is good to explain blocks of commands so that your successor can come in and make alterations if needed.

#this next line of code sets your working directory to “c:\temp”
Set-Location “c:\temp

Credit:  This is like citing your work on a paper.  It’s not only honest but necessary if the code needs to be manipulated. If no author is presented, verify the code and put down the web address where you found it. Remember, DO NOT USE CODE YOU CANNOT EXPLAIN.  Period.

#this next block of code was provided by Jane Doe via  Her email address is

Temporary editing:  When you’re working with code and are not sure if your modifications are right, comment out the original section and start from scratch.  This will keep you from getting lost in your purpose and provides you with the opportunity to revert to the original block of commands.

#remove-item “c:\temp\*.*
Remove-item “c:\temp\*.log

With that being said the two commands you need to know are # and <# #>.  # comments out 1 line in a script and is best used when you only have one line to comment.

#remove-item “c:\temp\*.*

This will make Powershell ignore your command so long as # precedes it.  Block commenting is used for most everything else.  Simply Precede the block of commands with <# and succeed it with #>:

Set-Location “c:\temp
$foo = “foo.txt

Do you have anything to add? Do you have corrections or Kudo’s?  Please leave a comment below! And remember, a share and a +1/like/tweet go a long way!

1 comment:

  1. Very nice "best practices." As someone new to scripting, it's a great reminder to develop good habits from the beginning.