Powershell中的函数参数验证



为什么在这个例子中,一个[string]与'值'$null的强制转换参数永远不会抛出错误(空或$null),但一个值'$null'的字符串总是抛出?我希望如果传递一个强制参数,它将检查$null/empty,因此在这些情况下总是抛出错误:

Function test_M_NoE ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $x ) {}
# test cases. Uncomment one:
[string]$x = [string]$null 
# $x = [string]$null
# [string]$x = $null
# $x = $null 
"1:"; test_M_NoE [string]$x # never error
"2:"; test_M_NoE $x         # always error

原因:

test_M_NoE [string]$x

是否[string]$x而不是以您期望的方式被解释。

让我们改变你的测试函数定义,以帮助我们更好地看到实际发生了什么:

function test_M_NoE {
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$x
)
Write-Host "Argument value passed was: '$x'"
}

现在,让我们再试一次:

PS ~> $x = $null
PS ~> test_M_NoE [string]$x
Argument value passed was: '[string]'

啊哈!参数表达式[string]$x没有导致空字符串-它导致字面值字符串值[string]

这是因为PowerShell试图以不同的方式解析命令参数。来自about_Parsing帮助主题:

参数模式是为解析shell环境中命令的参数和参数而设计的。所有输入都被视为可扩展字符串除非它使用以下语法之一:[…]

实际上,PowerShell将参数表达式解释为双引号字符串:

test_M_NoE "[string]$x"

此时的行为是有意义的-$x$null,所以它的计算结果是一个空字符串,因此表达式"[string]$x"的结果就是[string]

将参数表达式包含在$(...)子表达式操作符中,使其作为值表达式计算,而不是作为可扩展字符串计算:

test_M_NoE $([string]$x)

最新更新