about_Booleans
简短说明
描述如何计算布尔表达式。
长说明
PowerShell 可以将任何类型隐式视为 布尔值。 请务必了解 PowerShell 用于将其他类型转换为 布尔 值的规则。
从标量类型转换
标量类型是一次只能容纳一个值的原子量。 以下类型计算结果为 $false
:
- 空字符串,如
''
或""
- Null 值,例如
$null
- 值为 的任意数值类型
0
示例:
PS> $false -eq ''
True
PS> if ("") { $true } else { $false }
False
PS> if ($null) { $true } else { $false }
False
PS> if ([int]0) { $true } else { $false }
False
PS> if ([double]0.0) { $true } else { $false }
False
以下类型计算结果为 $true
:
- 非空字符串
- 任何其他非集合类型的实例
示例:
# a non-collection type
PS> [bool]@{value = 0}
True
# non-empty strings
PS> if ('hello') { $true } else { $false }
True
PS> [bool]'False'
True
请注意,这与 显式字符串分析不同:
PS> [bool]::Parse('false')
False
PS> [bool]::Parse('True')
True
PS> [bool]::Parse('Not True')
MethodInvocationException: Exception calling "Parse" with "1" argument(s):
"String 'Not True' was not recognized as a valid Boolean."
从集合类型转换
数组是 PowerShell 中最常见的集合类型。 这些规则适用于实现 IList 接口的任何类似集合的类型。
- 空集合始终为
$false
- 指示命令
[System.Management.Automation.Internal.AutomationNull]::Value
中缺少输出的特殊 null 值始终$false
为 。 - 单元素集合的计算结果为其唯一元素的 布尔 值。
- 元素超过 1 的集合始终
$true
为 。
示例:
# Empty collections
PS> [bool]@()
False
PS> [bool](Get-ChildItem | Where-Object Name -eq 'Non-existent-File.txt')
False
# Single-element collections
PS> $a = @(0)
PS> [bool]$a
False
PS> $b = @(1)
PS> [bool]$b
True
# Multi-element collections
PS> $c = @(0,0)
PS> [bool]$c
True
另请参阅
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
PowerShell
A cross-platform task automation solution made up of a command-line shell and a scripting language.
反馈
提交和查看相关反馈