Powershell 中的函数参数验证
Function parameter validation in Powershell
为什么在此示例中带有 'value' $null 的 [string] 强制转换参数从不抛出错误(空或 $null),但值为 '$null' 的字符串总是抛出错误?我希望如果传递强制参数,它会被检查 $null/emptyness 因此在这些情况下总是会抛出错误:
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
help topic:
Argument mode is designed for parsing arguments and parameters for commands in a shell environment. All input is treated as an expandable string unless it uses one of the following syntaxes: [...]
实际上,PowerShell 将我们的参数表达式解释为双引号字符串:
test_M_NoE "[string]$x"
此时行为有意义 - $x
是 $null
,因此它的计算结果为空字符串,因此表达式 "[string]$x"
的结果只是 [string]
.
将参数表达式括在 $(...)
子表达式运算符中,使其作为值表达式而不是可扩展字符串求值:
test_M_NoE $([string]$x)
为什么在此示例中带有 'value' $null 的 [string] 强制转换参数从不抛出错误(空或 $null),但值为 '$null' 的字符串总是抛出错误?我希望如果传递强制参数,它会被检查 $null/emptyness 因此在这些情况下总是会抛出错误:
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
help topic:
Argument mode is designed for parsing arguments and parameters for commands in a shell environment. All input is treated as an expandable string unless it uses one of the following syntaxes: [...]
实际上,PowerShell 将我们的参数表达式解释为双引号字符串:
test_M_NoE "[string]$x"
此时行为有意义 - $x
是 $null
,因此它的计算结果为空字符串,因此表达式 "[string]$x"
的结果只是 [string]
.
将参数表达式括在 $(...)
子表达式运算符中,使其作为值表达式而不是可扩展字符串求值:
test_M_NoE $([string]$x)