Nipun
Nipun

Reputation: 2261

Multiline comment in PowerShell

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.

Upvotes: 149

Views: 82412

Answers (3)

iLikeToHike
iLikeToHike

Reputation: 1

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)

Upvotes: 0

ForNeVeR
ForNeVeR

Reputation: 6955

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

<# a
   b
   c #>

Upvotes: 251

&#220;berUser123
&#220;berUser123

Reputation: 71

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.

Upvotes: 7

Related Questions