146

Can we comment multiple lines together in PowerShell?

I tried looking, but I didn't find any answer. It's quite irritating to comment each line manually if the script is too long.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nipun
  • 2,217
  • 5
  • 23
  • 38
  • 2
    Possible duplicate of *[How do you comment out code in PowerShell?](https://stackoverflow.com/questions/7342597/how-do-you-comment-out-code-in-powershell)*. – Peter Mortensen Jul 23 '18 at 08:05

3 Answers3

248

In PowerShell v2 and newer, use the following syntax for the multiline comments:

<# a
   b
   c #>
ForNeVeR
  • 6,726
  • 5
  • 24
  • 43
  • 3
    Perhaps say something about [PowerShell versions this is supported in](https://stackoverflow.com/questions/7342597/how-do-you-comment-out-code-in-powershell/7344038#7344038). – Peter Mortensen Jul 23 '18 at 08:03
7

The multiline comment in PowerShell should work.

If not, try this...

# This is
# a
# multiline comment.

or

<#
This does works for me.
#>

If it doesn't work, try to check if you have the correct version of PowerShell.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ÜberUser123
  • 71
  • 1
  • 4
0

I hate needing to manually add comment characters. So here is an answer to your (perhaps) implied question, "How can I comment out multiple lines without manually adding comment characters?" I searched around for a hotkey solution and found one I like at https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/toggling-comments-in-powershell-ise.

It works for one or many lines, or even within lines. Place this function in your $Profile file.

function Toggle-Comment
{
    $file = $psise.CurrentFile                              
    $text = $file.Editor.SelectedText   
    if ($text.StartsWith("<#")) {
        $comment = $text.Substring(2).TrimEnd("#>") 
    }
    else
    {                            
        $comment = "<#" + $text + "#>"    
    }
    $file.Editor.InsertText($comment)                     
}

$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Toggle Comment', { Toggle-Comment }, 'CTRL+K')

$Profile is run every time ISE is opened, so the function is always available. The function creates a new menu item with keyboard shortcut Ctrl-K that comments or uncomments the selected lines.

If the $Profile file is not yet created (it's often not), you can create it like this:

New-Item -Path $profile -ItemType "file" -Force

(source for command: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-item?view=powershell-7.2)