[英]powershell checking boolean environment variable
I ran into something strange, and I don't understand what is happening:我遇到了一些奇怪的事情,我不明白发生了什么:
PS C:\> $env:x = $false
PS C:\> if($env:x){'what'}
what
PS C:\> $env:x
False
So the value is actually false, but what does the if
check?所以这个值实际上是假的,但是
if
检查什么呢? Clearly not the value of x
.显然不是
x
的值。 What is happening?怎么了?
The Environment
provider (which implements the env:
drive) only supports string items, and will coerce any assigned value to a [string]
: Environment
提供程序(实现env:
驱动器)仅支持字符串项目,并将强制任何分配的值到[string]
:
PS C:\> $env:x = $false
PS C:\> $env:x.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
... and the default [string]
-to- [bool]
conversion rules in PowerShell holds that non-empty strings are converted to $true
: ...并且 PowerShell 中的默认
[string]
-to- [bool]
转换规则认为非空字符串将转换为$true
:
PS C:\> $true -eq 'false'
True
PS C:\> [bool]'false'
True
PS C:\> [bool]''
False
To parse a string value (like "false"
) to its equivalent [bool]
value, you need to either call [bool]::Parse()
:要将字符串值(如
"false"
)解析为等效的[bool]
值,您需要调用[bool]::Parse()
:
if([bool]::Parse($env:x)){
'what'
}
... or, if the string value might not be a valid truthy/falsy value, use [bool]::TryParse()
: ...或者,如果字符串值可能不是有效的真值/假值,请使用
[bool]::TryParse()
:
$env:x = $false
$result = $false
if([bool]::TryParse($env:x, [ref]$result) -and $result){
'what'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.