gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:54:49 29 4
gpt4 key购买 nike

我有一个方法需要接受字符串数组作为参数,但该数组只能包含有效字符串。我的问题是,如果我确保 [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 : 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



我需要做什么才能允许 $null要传入,还要验证集合以确保适当的类型?

最佳答案

这里的答案是使用 [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

关于validation - 如何使用 ValidateSet 并仍然允许在数组参数上使用 $null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656593/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com