As a seasoned developer well-versed in many programming languages, I often get asked about best practices for writing maintainable, legible code. And one technique I always emphasize is robust commenting using multiline comment blocks.
Comments are the lifeblood of sustainable scripts that can be picked up months or even years later. And in the PowerShell world, multiline comments give developers immense flexibility to document logic flows, mark off sections, and leave detailed notes.
But interestingly, I‘ve noticed from code reviews that many developers don‘t take full advantage of multiline commenting capabilities. In this comprehensive guide, I‘ll share my insider tips for wielding multiline comments effectively from an expert developer‘s point of view.
Why Comments Matter More than You Think
Before jumping into the mechanics of multiline comments in PowerShell, it‘s worth stepping back on why commenting – and doing it well – is so critically important for any developer.
1. Code clarity for future developers
Odds are that you will not be the only person ever working on your PowerShell scripts. Even as a solo developer, you yourself may come back to edit your scripts months or years down the line with no recollection of how they work!
Without comments describing logic flows, future developers will have major difficulty interpreting and thus maintaining your code. Protect them by documenting extensively with comments while the script purpose is still fresh in your mind.
2. Facilitates code reviews
Code reviews are an essential check on quality for teams practicing collaborative development. And nothing frustrates reviewers more than wading through complex scripts with no guiding comments!
Use multiline comments to segment functional blocks and provide orientation on the high-level approach. This builds empathy from reviewers to approve pull requests faster.
3. Encourages modification over abandonment
Ever inherit a legacy system with thousands of lines of business logic embedded, only to shy away since understanding it would require weeks of effort? Had the original authors commented appropriately, you could begin making enhancements immediately instead of considering starting from scratch.
Commented code gives future developers the confidence to build on top of existing scripts vs. the temptation to rebuild. This saves organizations huge sums over the long-run.
4. Embeds invaluable architectural knowledge
Well constructed PowerShell scripts often exemplify carefully orchestrated workflows reflecting an enterprise architecture vision. The developers who architects system workflows acquire deep business domain knowledge.
Comments provide a vessel for architects and key designers to encode this hard-won vision directly alongside implementation logic as guidance to future maintainers. Protect institutional knowledge by documenting architectural frameworks thoroughly!
Okay I‘m Convinced! Now Let‘s Code It Right
Now that I‘ve hopefully made a case for why commenting – and specifically multiline comments – are not just a "nice to have" but a "must have", let‘s dig into practical application.
Based on inspecting thousands of PowerShell codebases, I‘ve compiled tips on using multiline comments masterfully. Print this guide out and keep it pinned above your desk!
Follow Standard Comment Guideposts
Effective comments tell a coherent story and bring order to complexity through consistent positioning:
1. Introduction
Summarize script purpose, key capabilities, author info at the top comments:
<#
Script Name: Get-LargeLogFiles.ps1
Author: John Developer
Created On: January 1 2020
Searches server logs daily and emails alerts for
any log over 25MB in size for storage monitoring.
#>
2. Configuration Section
Denote any config parameters that may need tuning:
<#
CONFIG VALUES
$LogRoot = "C:\Logs" # Root directory to search logs
$SizeThreshold = 25MB # Alert threshold
$EmailTo = "admin@company.com"
#>
3. Function/Method Headers
Document purpose, arguments, outputs for each function before logic:
<#
.SYNOPSIS
Helpers that filters log file objects over size threshold
.DESCRIPTION
Accepts array of FileInfo objects on pipeline input.
Outputs only those over configured $SizeThreshold variable.
#>
Filter Find-LargeFiles {
param (
[System.IO.FileInfo[]] $LogFile
)
foreach ($file in $LogFile) {
if ($file.Length -gt $SizeThreshold) {
Write-Output $file
}
}
}
4. Complex Logic Sections
Call out intricate workflows and custom algorithms:
<#
Interpolate log timestamps from previous good event since
logs rotated hourly and may have gaps in sequential ordering.
#>
$lastGoodEventTime = 0
foreach ($event in $Events) {
if (!$event.Timestamp) {
$event.Timestamp = $lastGoodEventTime
}
else {
$lastGoodEventTime = $event.Timestamp
}
}
5. TODOs and Open Issues
Use comments to annotate areas requiring further work:
<#
TODO: Refactor Filter logic into separate module
and import to improve performance
#>
Adhering to standard commenting patterns improves navigation and comprehension for future readers.
Don‘t Forget Closing Comments!
Bookending scripts with opening and closing comments prevents ambiguity:
1. Initialization Check
<#
Runtime startup checks passed!
#>
#Script logic starts here
2. Execution Report
# Script logic ends
<#
Script executed successfully at $(Get-Date)!
Files over threshold:
$LargeFiles
#>
3. Revision History
<#
Revision History:
1.0 - 1/1/2020 - Initial version by John Developer
1.1 - 2/15/2020 - Improved logging by Jane Engineer
1.2 - 5/30/2020 - Upgraded email module
#>
This leaves future developers little room for doubt on what occurred during execution.
Embrace Creative Comment Content
Don‘t limit yourself to high level narratives – great comments enrich understanding through visuals, external references and illustrative examples:
Diagrams
<#
+------------+ +---------------+
| Ingestion | --> Event --> | Enrichment Hub| --> Analytics
+------------+ +---------------+
^ |
| Formatters |
+-------------------------+
#>
Links
<#
For info on the Fluentd log collector architecture we utilized, see:
https://docs.fluentd.org/architecture
#>
Code Examples
<#
For example to search PowerShell event logs:
Get-EventLog -LogName "PowerShellCore/Operational" -After 1/1/2020
#>
Varying comment content type keeps readers engaged across lengthy technical scripts.
Follow Pro Tips for Multiline Style
After years assessing others‘ code, I‘ve compiled key tips on crafting clean, useful multiline comments:
- Breakinto paragraphs – Comments read easier in digestable blocks over walls of texts. Separate distinct ideas.
- Use consistent prefixes – Many scripts prefix multiline comments with ".NOTES" or ".DESCRIPTION" for quick identification. I personally like ".DOCUMENTATION". Find standards your team values.
- Note unit expectations and thresholds– For functions accepting interval timing parameters, specify units are seconds, minutes, etc. For size thresholds, note if units are bytes, kilobytes, etc.
- Call out dependencies and requirements – Highlight external services, data stores or configurations required for intended functionality.
- Record error and warning scenarios – Use comments to encode potential failure scenarios and suggested mitigations based on past issues to save others time.
- Diagram hierarchies and relationships – Visually represent nested hierarchies of objects or orchestration dependencies using comments.
- Watch character length per line– Strive to keep comment lines under 80 characters for readability best practices.
- Leverage code collapse – In tools like VisualStudio, lengthy comments can be collapsed allowing devs to focus on code logic.
Hopefully these tips sharpen your multiline commenting skills! Follow them closely in your next PowerShell project.
Comment First, Code Second: An Underused Strategy
Now for an advanced commenting technique I wish more developers would embrace. Try switching the standard coding sequence:
The usual scripting approach goes:
- Code logic
- Sprinkle some comments
Flip it entirely upside down with:
- Write documentation first
- Then code to match
By thoroughly commenting a script structure before implementing, you deeply engage analytical thinking to capture intricacies often glossed over otherwise. The resulting script reads like pseudocode intermixed with documentation.
For example, first write:
<#
.SYNC DELETED FILES WITH CLOUD
Iterate through all folders recursively
If local file not found in cloud
Upload file
Else If cloud file not found locally
Flag file for deletion
Handle Errors:
Log upload failure alerts
Retry transient cloud errors
#>
# TODO: Add logic here
Not only have you mapped expected logic flows prior to coding, reviewers can validate design direction before real work begins!
Now start replacing TODO stubs with real code until a full implementation emerges. Don‘t break rhythm documenting additional insights uncovered mid-development either.
I admit upfront documentation is still an avant-garde ritual even amongst hardcore developers. But teams willing to pioneer rigorous commenting-focused processes will undoubtedly craft next generation maintainable codebases.
Final Thoughts
There is no separating quality sustainable code from judicious commenting strategy. While PowerShell offers flexible multiline comment options, simple existence alone is not enough. Developers must harness this capability by:
- Understanding how essential commenting is for downstream usage
- Standardizing on consistent commentingguideposts
- Enhancing insight through diverse content
- Mastering best practice stylistic principles
- Inverting development flow comment-first
Follow these recommendations in your PowerShell practice to ensure your code leaves a lasting legacy for you, your teammates and future maintainers!
What commenting wisdom can you impart? I welcome hearing your top tips through my blog below!


