Как вы закомментируете код в PowerShell?

Как вы закомментируете код в PowerShell (1.0 или 2.0)?

11 ответов

Решение

В PowerShell V1 есть только # сделать текст после него комментарием.

# This is a comment in Powershell

В PowerShell V2 <# #> может использоваться для блочных комментариев и, более конкретно, для справочных комментариев.

#REQUIRES -Version 2.0

<#
.SYNOPSIS
    A brief description of the function or script. This keyword can be used
    only once in each topic.
.DESCRIPTION
    A detailed description of the function or script. This keyword can be
    used only once in each topic.
.NOTES
    File Name      : xxxx.ps1
    Author         : J.P. Blanc (jean-paul_blanc@silogix-fr.com)
    Prerequisite   : PowerShell V2 over Vista and upper.
    Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
    Script posted over:
    http://silogix.fr
.EXAMPLE
    Example 1
.EXAMPLE
    Example 2
#>
Function blabla
{}

Для получения дополнительной информации о .SYNOPSIS а также .* см. about_Comment_Based_Help.

Замечание: эти комментарии функции используются Get-Help CmdLet и можно поставить перед ключевым словом Functionили внутри {} до или после самого кода.

Вы используете хеш-знак, как это

# This is a comment in Powershell

В Википедии есть хорошая страница для отслеживания того, как делать комментарии на нескольких популярных языках.

http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(syntax)

Однострочные комментарии начинаются с символа хеша, все справа от # будет проигнорировано:

# Comment Here

В PowerShell 2.0 и выше могут использоваться многострочные комментарии:

<# 
  Multi 
  Line 
#> 

Вы можете использовать блочные комментарии для встраивания текста комментариев в команду:

Get-Content -Path <# configuration file #> C:\config.ini

Примечание. Поскольку PowerShell поддерживает завершение вкладок, необходимо соблюдать осторожность при копировании и вставке. Space + TAB до комментариев.

Это #,

См. PowerShell - Специальные символы и токены для специальных символов.

В PowerShell ISE вы можете нажать Ctrl+J, чтобы открыть меню Start Snipping и выбрать блок комментариев:

введите описание изображения здесь

Вот

# Single line comment in Powershell

<# 
--------------------------------------
Multi-line comment in PowerShell V2+ 
-------------------------------------- 
#>

Используйте для этого хэштег, за которым следует пробел (!):

 # comment here

Не забывайте здесь пробелы! В противном случае это может помешать внутренним командам.

Например, это НЕ комментарий:

#requires -runasadmin

Я немного опоздал на эту вечеринку, но кажется, что на самом деле никто не написал все варианты использования. Так...

В настоящее время (осень 2020 г. и позже) поддерживаются только следующие версии PowerShell:

  • Windows PowerShell 5.1.x
  • PowerShell 7.0.x.

You don't want to or you shouldn't work with different versions of PowerShell.

Both versions (or any another version which you could come around WPS 3.0-5.0, PS Core 6.x.x on some outdated stations) share the same comment functionality.

One line comments

# Get all Windows Service processes <-- one line comment, it starts with '#'
Get-Process -Name *host*

Get-Process -Name *host* ## You could put as many ### as you want, it does not matter

Get-Process -Name *host* # | Stop-Service # Everything from the first # until end of the line is treated as comment

Stop-Service -DisplayName Windows*Update # -WhatIf # You can use it to comment out cmdlet switches

Multi line comments

<#
Everyting between '< #' and '# >' is 
treated as a comment. A typical use case is for help, see below.

# You could also have a single line comment inside the multi line comment block.
# Or two... :)

#>

<#
.SYNOPSIS
    A brief description of the function or script.
    This keyword can be used only once in each topic.

.DESCRIPTION
    A detailed description of the function or script.
    This keyword can be used only once in each topic.

.NOTES
    Some additional notes. This keyword can be used only once in each topic.
    This keyword can be used only once in each topic.

.LINK
    A link used when Get-Help with a switch -OnLine is used.
    This keyword can be used only once in each topic.

.EXAMPLE
    Example 1
    You can use this keyword as many as you want.

.EXAMPLE
    Example 2
    You can use this keyword as many as you want.
#>

Nested multi line comments

<#
Nope, these are not allowed in PowerShell.

<# This will break your first multiline comment block... #>
...and this will throw a syntax error.
#>

In code nested multi line comments

<# 
The multi line comment opening/close
can be also used to comment some nested code
or as an explanation for multi chained operations..
#>
Get-Service | <# Step explanation #>
Where-Object { $_.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped } | 
<# Format-Table -Property DisplayName, Status -AutoSize |#>
Out-File -FilePath Services.txt -Encoding Unicode

Edge case scenario

# Some well written script
exit
Writing something after exit is possible but not recommended.
It isn't a comment.
Especially in Visual Studio Code, these words baffle PSScriptAnalyzer.
You could actively break your session in VS Code.

Ты можешь сделать:

 (Some basic code) # Use "#" after a line and use:

 <#
    for more lines
    ...
    ...
    ...
    ..
    .
 #>

Есть специальный способ вставки комментариев в конец скрипта:

....
exit 

Hi
Hello
We are comments
And not executed 

Что-нибудь после exit не выполняется и ведет себя как комментарии.

Комментарии делаются с помощью # ключ.

Например,

      # Run Command Prompt
Start cmd.exe
Другие вопросы по тегам