【发布时间】:2021-10-26 23:40:08
【问题描述】:
如何在 PowerShell 中强制设置参数?
【问题讨论】:
标签: powershell
如何在 PowerShell 中强制设置参数?
【问题讨论】:
标签: powershell
您在每个参数上方的属性中指定它,如下所示:
function Do-Something{
[CmdletBinding()]
param(
[Parameter(Position=0,mandatory=$true)]
[string] $aMandatoryParam,
[Parameter(Position=1,mandatory=$true)]
[string] $anotherMandatoryParam)
process{
...
}
}
【讨论】:
Position...
要使参数成为强制性参数,请在参数说明中添加“Mandatory=$true”。要使参数成为可选参数,只需将“强制”语句省略即可。
此代码适用于脚本和函数参数:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$aMandatoryParameter,
[String]$nonMandatoryParameter,
[Parameter(Mandatory=$true)]
[String]$anotherMandatoryParameter
)
确保“param”语句是脚本或函数中的第一个语句(cmets 和空行除外)。
您可以使用“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?
【讨论】:
只是想发布另一个解决方案,因为我发现 param(...) 块有点难看。
看起来像这样的代码:
function do-something {
param(
[parameter(position=0,mandatory=$true)]
[string] $first,
[parameter(position=1,mandatory=$true)]
[string] $second
)
...
}
也可以更简洁地写成这样:
function do-something (
[parameter(mandatory)] [string] $first,
[parameter(mandatory)] [string] $second
) {
...
}
看起来好多了! =$true 可以省略,因为mandatory 是一个开关参数。
(免责声明:我对 PS 还很陌生,这个解决方案可能有一些我不知道的极端情况。如果是这样,请告诉我!)
【讨论】:
你不必指定Mandatory=true,Mandatory 就足够了。
简单示例:
function New-File
{
param(
[Parameter(Mandatory)][string]$FileName
)
New-Item -ItemType File ".\$FileName"
}
【讨论】: