我目前正在撰写一份简单的PowerShell(5)书。 它应当吸收用户的意见,然后根据投入执行一些任务。 我将Validate写到投入参数,以验证用户的投入。 根据PowerShell文件,验证是在编码操作之前进行的,因此,我改变了用户投入的价值。 然而,这造成了错误。
考虑下面的简单例子。
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateScript({ $_ -gt 0 })]
[int]$InputParameter
)
process {
$InputParameter = -1
}
}
Running
TEST-FUNCTION 0
Yields an error
TEST-FUNCTION : Cannot validate argument on parameter InputParameter . The " $_ -gt 0 " validation script for the
argument with value "0" did not return a result of True. Determine why the validation script failed, and then try the
command again.
At line:1 char:15
+ TEST-FUNCTION 0
+ ~
+ CategoryInfo : InvalidData: (:) [TEST-FUNCTION], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,TEST-FUNCTION
这具有意义,因为它没有通过最初的确认。
However, running
TEST-FUNCTION 1
also yields an error.
The variable cannot be validated because the value -1 is not a valid value for the InputParameter variable.
At line:12 char:9
+ $InputParameter = -1
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ValidationMetadataException
+ FullyQualifiedErrorId : ValidateSetFailure
The two function calls give two different errors. I’m not sure why I can’t change the value of the parameter after it has passed validation. Is there any workaround that can prevent the second round of evaluation? Thanks!