Powershell multi-line comments - Svendsen Tech
Jump to page sections

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. In Windows 10, you have Windows PowerShell 5.1 and optionally PowerShell Core.

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 (executable location link) with default syntax highlighting:

$Computers = Get-ADComputer -Filter *

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

$Computers | ForEach-Object {$_.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 "@", where the latter will interpolate/expand/substitute variables. Then you pipe it to Out-Null to suppress output. See the examples below.

Be aware that you need to put the closing delimiter ('@ or "@) on its own line and at the start of the line. Also be aware that the safest choice is single quotes.

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, powershell core windows powershell,

    Powershell     Windows     Syntax     All Categories

Google custom search of this website only

Minimum cookies is the standard setting. This website uses Google Analytics and Google Ads, and these products may set cookies. By continuing to use this website, you accept this.

If you want to reward my efforts