Comments

It is very important to include meaningful comments in your script. There are generally two types of comment: single line and block comments.

When commenting your code, you should always try to be concise and describe parts of your code that are not self-explanatory. In general, PowerShell cmdlets lend themselves to self-documenting code. To improve readability, always include a whitespace after a hashtag. Short comments can also be written inline, after your line of code:

# Bad

# Sets value to 42
$illegibleVariable = 42

# Good

# Initialize repetition interval for scheduled task
$taskRepetitionMinutes = 42

Block comments are useful when a comment is longer, such as a header or disclaimer. They are usually used when writing comment-based help. Try to keep your comments short in your scripts.

Special types of comment include regions and requirements. Regions are perfectly suited to give your code some structure, and they can be folded. Regions are commonly used in .NET development as well to separate public and private properties, events, methods, and more:

#region A region name may contain whitespaces
Code goes between the region
#endregion

#region Regions can be
#region nested
Code
#endregion
#endregion

Requirements can be expressed in the form of a requires statement. This statement is always preceded by a hashtag, like a comment, without whitespace. A requires statement should always be placed at the top of a script:

#requires -Version 5.1 -RunAsAdministrator
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset