I was giving a presentation to the Austin PowerShell User Group last week and the group took notice when I quickly commented and uncommented lines in my PowerShell script in VS Code. You can easily add a PowerShell comment with the built-in keyboard shortcuts in Visual Studio and Visual Studio Code.
What is a PowerShell Comment?
First, there are a couple of types of comments in PowerShell. There are line comments and block comments. Line comments are denoted with a #. For example, you could include the following comment.
# # Hello. This is a comment #
Everything after the # will not be executed by PowerShell.
The second kind of comment is a block comment. A block comment allows you to comment sections of code with start and end tokens. To start a block token, you should use the <# token. To end the comment, use the #> token. For example, we could create the following comment.
<# Hello. This is a comment. #>
Everything between the <# and #> will not be executed by PowerShell. You can also use block comments directly in-line with other scripts. For example, you could include a block comment right in a cmdlet call.
Get-Process <# -Id 12 #> -Name 'Notepad'
How do I comment and uncomment PowerShell in Visual Studio Code and Visual Studio?
First, select the lines you want to comment out. To comment out the selected lines, press:
Ctrl+K, Ctrl+C
If you want to uncomment the selected lines, you can use the reverse keyboard shortcut:
Ctrl+K, Ctrl+U
Here’s a demo in VS Code.
The same keyboard shortcuts work in Visual Studio.
How do I toggle PowerShell comments in Visual Studio Code?
You can also toggle comments using the following keyboard shortcut.
Ctrl + /
This works in Visual Studio Code but not Visual Studio.
How do I toggle PowerShell block comments in Visual Studio Code?
If you wish to use a block comment in Visual Studio Code, you can use the following shortcut.
This works in Visual Studio Code but not Visual Studio.
Shift + Alt + A