如何为Powershell脚本参数显示帮助消息?

问题描述 投票:53回答:3

我有一个powershell脚本(setup.ps1),我们将其用作开发环境设置脚本的入口点。它需要一个参数:

param(
    [Parameter(Position=0,HelpMessage="The targets to run.")]
    [Alias("t")]
    [string[]]
    $Targets = "Help"
)

我跑的时候

PS > get-help .\setup.ps1 -detailed

在参数部分,我的帮助消息没有出现:

PARAMETERS
    -Targets <String[]>

我需要做什么才能显示参数帮助消息?

powershell powershell-v2.0
3个回答
90
投票

您在文件的顶部放置了某种注释样式,可以通过PowerShell帮助系统进行解码。这是一个例子:

<#
.SYNOPSIS
    .
.DESCRIPTION
    .
.PARAMETER Path
    The path to the .
.PARAMETER LiteralPath
    Specifies a path to one or more locations. Unlike Path, the value of 
    LiteralPath is used exactly as it is typed. No characters are interpreted 
    as wildcards. If the path includes escape characters, enclose it in single
    quotation marks. Single quotation marks tell Windows PowerShell not to 
    interpret any characters as escape sequences.
.EXAMPLE
    C:\PS> 
    <Description of example>
.NOTES
    Author: Keith Hill
    Date:   June 28, 2010    
#>
function AdvFuncToProcessPaths
{
    [CmdletBinding(DefaultParameterSetName="Path")]
    param(
        [Parameter(Mandatory=$true, Position=0, ParameterSetName="Path", 
                   ValueFromPipeline=$true, 
                   ValueFromPipelineByPropertyName=$true,
                   HelpMessage="Path to ...")]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Path,

        [Alias("PSPath")]
        [Parameter(Mandatory=$true, Position=0, ParameterSetName="LiteralPath", 
                   ValueFromPipelineByPropertyName=$true,
                   HelpMessage="Path to ...")]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $LiteralPath
    )
    ...

有关更多信息,请参阅帮助主题 - man about_comment_based_help


19
投票

显然,如果你定义了一个帮助头,你可以在参数后面使用一个注释(#)(在这个例子中:#要运行的目标。):

<#
.SYNOPSIS
    .
.DESCRIPTION
    .
.PARAMETER Path
    The path to the .
.PARAMETER LiteralPath
    Specifies a path to one or more locations. Unlike Path, the value of 
    LiteralPath is used exactly as it is typed. No characters are interpreted 
    as wildcards. If the path includes escape characters, enclose it in single
    quotation marks. Single quotation marks tell Windows PowerShell not to 
    interpret any characters as escape sequences.
#>

Param(
    [String]$Targets = "Help"   #The targets to run.
)

结果是:

PS C:\> Get-help .\Setup.ps1 -Detailed

NAME
    C:\Setup.ps1

SYNOPSIS
    .


SYNTAX
    C:\Setup.ps1 [[-Targets] <String>] [<CommonParameters>]


DESCRIPTION
    .


PARAMETERS
    -Targets <String>
        The targets to run.

2
投票

一个只需要在文件顶部的<# .SYNOPSIS #>部分使其工作,你可以很好地内联评论你的params:

<# .SYNOPSIS #>
param(
   [String]$foo   ## my 1st cool param
  ,[Switch]$bar  ## my 2nd crazy switch
)
...

(与PS 5.1.14409.1018核实)

© www.soinside.com 2019 - 2024. All rights reserved.