Powershell multi-line comments

From Svendsen Tech PowerShell Wiki
Jump to: navigation, search

Multi-line Comments in PowerShell v2 and later

With PowerShell 2.0 came multi-line comments. They start with "<#" and end with "#>". They can be placed anywhere (except inside strings, but that's sort of a given), and anything between them will be treated as a comment. PowerShell 2.0 comes built-in with Windows 7 and Server 2008 R2.

A screenshot with syntax highlighting in the PowerShell ISE editor is handy to demonstrate (text versions below). This is as it appears in powershell_ise.exe with default syntax highlighting (and intellisense):

PowerShell-multiline-comments-example.png

$computers = Get-QADComputer -SizeLimit 0

<# This is the start of the comment.
This is some stuff in the middle.
and this is the end #>

$computers | %{ $_.Name }

<#
I like using them like this, where they're the only thing on the line.
#>

'Done'




Hacking Multi-line Comments in PowerShell v1

To get a multi-line comment in PowerShell version 1, you can "hackishly" use so-called here strings to "comment out" multiple lines / a block of code. You do this simply by enclosing the code snippet in either "@' contents '@" or "@" contents "@". Then you pipe it to Out-Null to suppress output. See examples below.

@'
the code
to comment
out, possibly
containing 's and "s goes
here. Variables will NOT be expanded/interpolated
in a single-quoted here string.
'@ | Out-Null

... or

@"
the code
to comment
out, possibly containing 's
and "s goes here.
Variables will be expanded/interpolated in
a double-quoted here string.
"@ | Out-Null

Single-line Comments

Single-line comments start with a hash sign: "#". They can be placed almost anywhere (of course not inside strings) and will make the rest of the line a comment.

$LogFiles = dir c:\windows -filter '*.log'

# This function does cool stuff
Some-Function $with $arguments # and another comment here

### This is another single-line comment
# and another




Keywords: comment out, add comment, comment that spans multiple lines, comment out a block, block comment powershell version 1, v1, v2