使参数组成为必需参数

时间:2016-02-18 14:09:28

标签: powershell arguments

如何让PowerShell脚本接受0或3个参数?全有或全无。

-O3

2 个答案:

答案 0 :(得分:0)

试试这个

Param(
    [Parameter(Mandatory=$True, Position=0, ParameterSet="FirstSet")]
    [string]FirstRequiredParam,

    [Parameter(Mandatory=$False, Position=0, ParameterSet="SecondSet")]
    [string]FirstNotRequiredParam
)

答案 1 :(得分:0)

这是简化的代码段

[CmdletBinding()]
Param(
    # Name of VPN connection
    [Parameter(Mandatory=$True, ParameterSetName="WithParams")]
    [string]$name,  

    # Server URL or IP
    [Parameter(Mandatory=$True, ParameterSetName="WithParams"))]
    [string]$vpn_server,


    # No params
    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=0, ParameterSetName="NoParams")]
    [string]$none
)

# Then check what parameters set was passed
switch ($PsCmdlet.ParameterSetName){
    "WithParams"  { Write-Host $name; break}
    "NoParams"    { Write-Host "No params passed."; break }
}