4

I've got a method that needs to accept an array of strings as a parameter, but that array can only contain valid strings. My problem is that if I ensure to [AllowNull()], and also [AllowEmptyCollection()], the method still fails

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 : Cannot validate argument on parameter 'authTypes'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. At line:16 char:32 + SomethingSomethingAuthType $null + ~~~~~ + CategoryInfo : InvalidData: (:) [SomethingSomethingAuthType], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,SomethingSomethingAuthType

What do I need to do to allow $null to be passed in, but also validate the set to ensure the appropriate types?

1 Answer 1

6

The answer here would be to use an [Enum[]] instead of [array], and remove the ValidateSet all together.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.