如何在PowerShell中强制创建参数?
您可以在每个参数上方的属性中指定它,如下所示:
function Do-Something{
[CmdletBinding()]
param(
[Parameter(Position=0,mandatory=$true)]
[string] $aMandatoryParam,
[Parameter(Position=1,mandatory=$true)]
[string] $anotherMandatoryParam)
process{
...
}
}
要使参数成为必需参数,请在参数说明中添加“Mandatory = $ true”。要使参数可选,只需保留“强制”语句即可。
此代码适用于脚本和函数参数:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$aMandatoryParameter,
[String]$nonMandatoryParameter,
[Parameter(Mandatory=$true)]
[String]$anotherMandatoryParameter
)
确保“param”语句是脚本或函数中的第一个(注释和空行除外)。
您可以使用“Get-Help”cmdlet验证参数是否已正确定义:
PS C:\> get-help Script.ps1 -full
[...]
PARAMETERS
-aMandatoryParameter <String>
Required? true
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters?
-NonMandatoryParameter <String>
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters?
-anotherMandatoryParameter <String>
Required? true
Position? 3
Default value
Accept pipeline input? false
Accept wildcard characters?