gpt4 book ai didi

powershell - 是否可以在 PowerShell 中的 bool[] 中包含 [Nullable[bool]]

转载 作者:行者123 更新时间:2023-12-03 14:38:06 25 4
gpt4 key购买 nike

是否可以在 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

enter image description here

最佳答案

这是 bool 类型的限制。严格输入参数时,只能取$true , $false , 0 , 和 1 .为了实现你想要的,你可以使用 [ValidateSet]属性:

[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory)]
[ValidateSet($null, $true, $false)]
[object] $ThisValue
)

作为旁注,在比较 $null 时,powershell 曾经存在一个错误(可能仍然存在)。右边会导致什么都不返回,导致逻辑掉出语句,所以最好比较左边:
if ($null -eq $ThisValue) {

在测试您的示例后,我无法复制您的问题,但是:
function Test-Nullable {
[CmdletBinding()]
param(
[nullable[bool]] $Value
)

if ($null -eq $Value) {
'Yes'
} else {
$Value
}
}

并以数组格式:
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

关于powershell - 是否可以在 PowerShell 中的 bool[] 中包含 [Nullable[bool]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207288/

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