Jam*_*iec 50
您可以在每个参数上方的属性中指定它,如下所示:
function Do-Something{
[CmdletBinding()]
param(
[Parameter(Position=0,mandatory=$true)]
[string] $aMandatoryParam,
[Parameter(Position=1,mandatory=$true)]
[string] $anotherMandatoryParam)
process{
...
}
}
Run Code Online (Sandbox Code Playgroud)
llm*_*ora 19
要使参数成为必需参数,请在参数说明中添加"Mandatory = $ true".要使参数可选,只需保留"强制"语句即可.
此代码适用于脚本和函数参数:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$aMandatoryParameter,
[String]$nonMandatoryParameter,
[Parameter(Mandatory=$true)]
[String]$anotherMandatoryParameter
)
Run Code Online (Sandbox Code Playgroud)
确保"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?
Run Code Online (Sandbox Code Playgroud)
不必指定Mandatory=true,Mandatory就足够了。
简单示例:
function New-File
{
param(
[Parameter(Mandatory)][string]$FileName
)
New-Item -ItemType File ".\$FileName"
}
Run Code Online (Sandbox Code Playgroud)
只是想发布另一个解决方案,因为我发现param(...)块有点丑。看起来像这样的代码:
function do-something {
param(
[parameter(position=0,mandatory=$true)]
[string] $first,
[parameter(position=1,mandatory=$true)]
[string] $second
)
...
}
Run Code Online (Sandbox Code Playgroud)
也可以更简洁地写成这样:
function do-something (
[parameter(mandatory)] [string] $first,
[parameter(mandatory)] [string] $second
) {
...
}
Run Code Online (Sandbox Code Playgroud)
这看起来好多了!所述=$true可以被省略,因为mandatory是一个开关参数。
(免责声明:我对 PS 还很陌生,这个解决方案可能有一些我不知道的极端情况。如果是这样,请告诉我!)