根据电源外壳中另一个参数的值设置 [参数(必需 = $true/$false)]



我正在PowerShell 3.0中编写一个函数。函数中的一个参数应设置为必需参数,具体取决于另一个参数的值。

函数 declaratioin 如下所示:

function removeVolumeandArrayFromHost(){
Param( [Parameter(mandatory = $true)] [ValidateSet('iSCSI','FC')] $arrayType, ##IpAddress/Name of the target host 
   [Parameter(mandatory = $true)] $volumeName, ##Name of the volume to be disconnected. (Volume name as in the array.)
   [Parameter(mandatory = $false)] $FCACL, ##Access control list name to which volume is added (Related to FC Array only)
   ## Work with the parameters given.
}

在上面的函数中,参数"$arrayType"可以具有值"iSCSI"或"FC"。

仅当 $arrayTpe = 'FC' 时,参数 $FCACL 才应该是必需的(必需 =

$true)。 如果$arrayType = 'iSCSI',则$FCACL参数不应是必需的(必需 = $false)

我尝试使用参数etname,但它确实有帮助,因为我需要查看参数的值$arrayType以确定$FCACL是否是强制性的。

任何类型的帮助或指示将不胜感激。

提前非常感谢。 :)

您可以使用

动态参数,或者如果您将$arrayType变量更改为开关,则可以使用ParameterSetName来强制操作。所以事情变得像这样:

Function removeVolumeandArrayFromHost(){
Param( 
    [Parameter(ParameterSetName="FC")][switch]$FC,
    [Parameter(ParameterSetName="iSCSI")][switch]$iSCSI,
    [Parameter(ParameterSetName="FC",Mandatory=$true)] [string]$FCACL,
    [Parameter(mandatory = $true)] [string]$volumeName
)
....
   ## Work with the parameters given.
}

或者,如果您知道您只处理 FC 或 iSCSI,那么您实际上只需要一个 switch 语句来说明它是否是 FC。如果-FC开关存在,则它将调用ParameterSetName=FC并需要 -FCACL 参数。如果排除-FC开关,则假定它是 iSCSI,ParameterSetName将确保您不需要-FCACL

Function removeVolumeandArrayFromHost(){
Param( 
    [Parameter(ParameterSetName="FC")][switch]$FC,
    [Parameter(ParameterSetName="FC",Mandatory=$true)] [string]$FCACL,
    [Parameter(mandatory = $true)] [string]$volumeName
)
....
   ## Work with the parameters given.
}

一种选择是使用函数的开始/进程/结束部分并在"开始"部分中处理此类内容,而不是像其他答案所建议的那样添加动态参数。

Chris N 给出的建议在我的情况下非常有效,因为我只需要以这种方式处理一个参数。我的理解是,如果处理许多此类参数,动态参数将是一个更好的选择。

为了更清楚起见,我在此处添加代码。

function removeVolumeandArrayFromHost(){
    Param( [Parameter(mandatory = $true)] [ValidateSet('iSCSI','FC')] $arrayType, ##IpAddress/Name of the target host 
       [Parameter(mandatory = $true)] $volumeName, ##Name of the volume to be disconnected. (Volume name as in the array.)
       [Parameter(mandatory = $false)] $FCACL) ##Access control list name to which volume is added (Related to FC Array only)       
    begin{
        if (($arrayType -eq 'FC') -and ($FCACL -eq $null)){
            Write-Error "For a FC Array, the FCACL parameter cannot be null."
            return
        }
    }
    process{
        .....
        .....
    }
}

感谢大家的意见和建议。我感谢您的帮助。

相关内容

最新更新