如何在PowerShell中强制使用参数?

Ale*_*x58 42 powershell

如何在PowerShell中强制创建参数?

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)

  • 很好的是,如果您不想这样做,甚至不必指定'= $ true'部分。“必需”是一个开关参数,因此它在装饰器中的存在表示其值“ $ true”。另外,如果愿意,可以将其显式设置为false。 (3认同)
  • 当您按默认顺序排列时,您不必指定“Position”... (3认同)

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)


Kol*_*yon 7

不必指定Mandatory=true,Mandatory就足够了。

简单示例:

function New-File
{
    param(
        [Parameter(Mandatory)][string]$FileName
    )

    New-Item -ItemType File ".\$FileName"
}
Run Code Online (Sandbox Code Playgroud)


ury*_*yga 6

只是想发布另一个解决方案,因为我发现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 还很陌生,这个解决方案可能有一些我不知道的极端情况。如果是这样,请告诉我!)