PowerShell函数中使用必选参数实例

本文介绍在PowerShell创建自定义函数时,如何添加必选参数,可以使用Mandatory关键词。

默认情况下,PowerShell自定义的函数中,参数都是可选的(optional)。如果要将一个参数设置为必选参数,那么必须对其设置Mandatory声明。

function Test-Function
{
    param(
        [Parameter(Mandatory=$true)]
        $p1,
        $p2='p2'
    )
    Write-Host "p1=$p1, p2=$p2"
}

在上面的示例函数中,参数$p1是必选参数,因为设置了Mandatory=$true,而$p2没有做任何设置,默认是可选的。按照PowerShell函数定义的Best Practices,可选参数都要设置一个默认值的,这点要记住。

在调用这个函数的时候,如果我们直接运行Test-Function而不输入参数,系统提示我们输入p1。

PS> Test-Function
cmdlet Test-Me at command pipeline position 1
Supply values for the following parameters:
p1:

顺便说一下,在PowerShell 3.0中,[Parameter(Mandatory=$true)] 这句可以简写成 [Parameter(Mandatory)],就是说“=$true”这一部分可以省略了。能少写点肯定少写点好,但如果少写了,放到PowerShell 3.0之前的环境——如PowerShell 2.0,那就无法运行了。看来鱼与熊掌不能得兼,我们还得要懂得取舍啊!

关于PowerShell函数设置必选参数,本文就介绍这么多,希望对您有所帮助,谢谢!