150

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.

1

3 Answers 3

254

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

<# a
   b
   c #>
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps say something about PowerShell versions this is supported in.
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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.