Even the simplest script languages, such as the batch interpreter cmd.exe, allow you to describe your code with comments. Of course, PowerShell also offers this feature. You can comment PowerShell code with single lines and in blocks.

PowerShell commentsPowerShell is an easy-to-read language because of its naming convention for cmdlets (verb–noun naming system with camel case capitalization) and its self-explanatory command words. Cryptic code such as in Perl is hardly possible with PowerShell unless you often use aliases. However, it is against best practices to use aliases in PowerShell scripts because you can’t assume that they have been defined on every computer.

Ensuring readability

Because of this, you will rarely need comments to explain what certain code does. Rather, you should document scripts with comments that describe what purpose certain functions or code blocks serve, so that your intentions become obvious.

If short explanations are sufficient, you can work with single-line comments. To this end, you have to append the text with the hash character, as in the following example:

Get-ADUser -Filter "Surname -like 'Ber*'"
 # Display AD user objects where the last name begins with "Bert"

For better readability, you should put even short comments on a separate line and not append them to the code. You also have to consider that, because of syntax highlighting, comments that look okay in PowerShell ISE might look confusing in a common text editor.

Comments with several lines

For longer explanations that consist of multiple lines, such as at the beginning of a script or a function, you don’t have to add a # to each line. As of version 2.0, PowerShell supports comment blocks:

Subscribe to 4sysops newsletter!

<# This is a comment 
 consisting of 
 multiple lines #>

Even though Microsoft follows the convention of other languages such as UNIX shells or Python with single-line comments, it goes its own way with comment blocks. The syntax in the form of /* comment */ that you might know from JavaScript or PHP is not allowed.


Leave a reply

Please enclose code in pre tags

Your email address will not be published.


© 4sysops 2006 - 2023


Please ask IT administration questions in the forums. Any other messages are welcome.


Log in with your credentials


Forgot your details?

Create Account