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

我有一个 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[]>

我需要做什么来显示我的参数帮助消息?

92176 次浏览

您在文件的顶部放置了某种风格的注释,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

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

<#
.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.

一个 只需要把 <# .SYNOPSIS #>放在上面的文件,使其工作,你可以 很好地注释你的参数:

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

(与 PS 5.1.14409.1018核对)