PowerShell 中的 bool[] 中是否可以包含 [Nullable[bool]]?我尝试了不同的解决方案、方法,但未能获得正确的 $null、$true、$false 参数?此外,[cmdletbinding] 似乎也改变了事物的工作方式。
enum BoolNull {
null = $null
true = $true
false = $false
}
function Test-Array0 {
param (
[bool[]] $thisValue
)
if ($thisValue -eq $null) {
Write-Output 'Null found'
}
}
function Test-Array1 {
param (
[bool[]] $thisValue
)
foreach ($value in $thisValue) {
if ($value -eq $null) {
Write-Output 'Null found'
}
}
}
function Test-Array2 {
[CmdletBinding()]
param (
[bool[]] $thisValue
)
if ($thisValue -eq $null) {
Write-Output 'Null found'
}
}
function Test-Array {
[CmdletBinding()]
param (
[AllowEmptyCollection()] [AllowNull()][ValidateSet($null, $true, $false)] $thisValue
)
if ($thisValue -eq $null) {
Write-Output 'Null found'
}
}
# this works
function Test-Test {
[CmdletBinding()]
param (
[nullable[bool]] $thisValue
)
if ($thisValue -eq $null) {
Write-Output 'Null found'
}
}
function Test-Array5 {
param (
[boolnull[]] $thisValue
)
foreach ($value in $thisValue) {
if ($value -eq 'null') {
Write-Output 'Null found'
}
}
}
Test-Array0 -thisValue $null #this works
Test-Array -thisValue $null # this doesn't work
Test-Array -thisValue $null, $null, $true # this doesn't work
Test-Array1 -thisValue $null
Test-Array2 -thisValue $null # this
Test-Test -thisValue $null # this works
Test-Array5 -thisValue null, true, null # this works but is completely useless
Run Code Online (Sandbox Code Playgroud)
这是 bool 类型的限制。当您严格输入参数时,只能采用$true、$false、0、 和1。为了实现你想要的,你可以使用一个[ValidateSet]属性:
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory)]
[ValidateSet($null, $true, $false)]
[object] $ThisValue
)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,powershell 曾经有一个错误(可能仍然存在),$null在右侧进行比较将导致不返回任何内容,导致逻辑脱离语句,因此最好在左侧进行比较:
if ($null -eq $ThisValue) {
Run Code Online (Sandbox Code Playgroud)
但是,在测试了您的示例后,我无法复制您的问题:
function Test-Nullable {
[CmdletBinding()]
param(
[nullable[bool]] $Value
)
if ($null -eq $Value) {
'Yes'
} else {
$Value
}
}
Run Code Online (Sandbox Code Playgroud)
并以数组格式:
function Test-Nullable {
[CmdletBinding()]
param(
[nullable[bool][]] $Value
)
foreach ($bool in $Value) {
if ($null -eq $bool) {
'Yes'
} else {
$bool
}
}
}
Test-Nullable 5, 3, $null, $true, $false, 0
True
True
Yes
True
False
False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |