如何使用ValidateSet并在Array参数上仍然允许$ null?

时间:2015-04-15 17:14:00

标签: validation powershell

我有一个方法需要接受一个字符串数组作为参数,但该数组只能包含有效的字符串。我的问题是,如果我确保[AllowNull()]以及[AllowEmptyCollection()],该方法仍然失败

function SomethingSomethingAuthType {
    param(
        [parameter(Mandatory=$true,position=0)] 
        [ValidateSet('anonymousAuthentication','basicAuthentication','clientCertificateMappingAuthentication','digestAuthentication','iisClientCertificateMappingAuthentication','windowsAuthentication')] 
        [AllowNull()] 
        [AllowEmptyCollection()] 
        [array] $authTypes
    )

    $authTypes | % {
        Write-Host $_ -f Green
    }

}

SomethingSomethingAuthType $null
  

SomethingSomethingAuthType:无法验证参数的参数   '使用authTypes'。参数为null,空或者是元素   参数集合包含空值。供应一个集合   不包含任何空值,然后再次尝试该命令。在   line:16 char:32   + SomethingSomethingAuthType $ null   + ~~~~~       + CategoryInfo:InvalidData:(:) [SomethingSomethingAuthType],ParameterBindingValidationException       + FullyQualifiedErrorId:ParameterArgumentValidationError,SomethingSomethingAuthType

我需要做些什么来传递$null,还要验证该集以确保适当的类型?

1 个答案:

答案 0 :(得分:5)

这里的答案是使用[Enum[]]代替[array],并一起删除ValidateSet。

function SomethingSomethingAuthType {
    param(
        [parameter(Mandatory=$true,position=0)] 
        [AllowNull()] 
        [AllowEmptyCollection()] 
        [AuthType[]] $authTypes
    )

    Write-Host 'Made it past validation.'

    if(!$authTypes) { return }

    $authTypes | % {
        Write-Host "type: $_" -f Green
    }

}

# Check if the enum exists, if it doesn't, create it.
if(!("AuthType" -as [Type])){
 Add-Type -TypeDefinition @'
    public enum AuthType{
        anonymousAuthentication,
        basicAuthentication,
        clientCertificateMappingAuthentication,
        digestAuthentication,
        iisClientCertificateMappingAuthentication,
        windowsAuthentication    
    }
'@
}
# Testing
# =================================

SomethingSomethingAuthType $null                                          # will pass
SomethingSomethingAuthType anonymousAuthentication, basicAuthentication   # will pass

SomethingSomethingAuthType invalid                                        # will fail
SomethingSomethingAuthType anonymousAuthentication, invalid, broken       # will fail