处理参数的好习惯是什么,何时选择哪个选项?
示例:通常我会写这样的函数:
function Do-Something ($variable1, $variable2, $variable3....)
{ Do Stuff }
现在显然这也是一个选择:
Param(
[Parameter(Position=0,
Mandatory=$True,
ValueFromPipeline=$True)]
[string]$userName,
...
)
但是,我可以不知道为什么要使用第二种,或者使用它的优点是什么。
答案 0 :(得分:6)
第二个Param()
块允许您进行大量高级参数验证。
如果我需要用最少的输入验证来编写一个简短的函数,我将使用这样的东西:
Function Test-Port ([string]$Server,[uint16]$Port=80,[uint16]$Timeout = 3000) {
#code here
}
但如果我需要用这样的高级检查来写一些东西:
function Get-SiteCert{
[CmdletBinding(DefaultParameterSetName = "Return")]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Server,
[Parameter(Position=1)]
[uint16]$Port=443,
[Parameter(Mandatory=$false, ParameterSetName="RawObj")]
[switch]$Raw,
[Parameter(Mandatory=$false, ParameterSetName="Export")]
[switch]$Export,
[Parameter(Mandatory=$true, ParameterSetName="Export")]
[string]$Path,
[uint16]$Timeout=3000
)
#code here
}
我绝对不会把它全部放到顶部栏中,即使它们是类似的脚本,第二个'确实'多很多。它实际上只是个案基础。
您可以查看this link有关使用扩展参数可以执行的操作的示例,但如果您不需要这些参数,请随时使用您喜欢的任何内容。
答案 1 :(得分:3)
正如@ConnorLSW在上面的回答中所写,验证是最大的好处之一。使用Param
块,您可以使用Validate
属性,例如:
Function Foo
{
Param(
[Parameter(Mandatory=$true,Position=0)]
[ValidateSet("Tom","Dick","Jane")]
[String]
$Name
,
[ValidateRange(21,65)]
[Int]
$Age
,
[ValidateScript({Test-Path $_ -PathType 'Container'})]
[string]
$Path
)
Process
{
write-host "New-Foo"
}
}
如果您的函数应支持不同的参数组合,您还可以定义不同的参数集。此外,您还可以获得#34;开箱即用"如果您是Get-Help
属性的Mandatory
和Positional
属性,请通过Parameter
提供文档。 E.g:
get-help Foo -Detailed
NAME
Foo
SYNTAX
Foo [-Name] {Tom | Dick | Jane} [[-Age] <int>] [-Path <string>] [<CommonParameters>]
PARAMETERS
-Age <int>
-Name <string>
-Path <string>
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).
ALIASES
None
REMARKS
None
根据Age
参数的括号,您可以选择它是一个可选参数。所以关于描述,验证和文档。
希望有所帮助。