Vivere
Vivere

Reputation: 2300

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? Clearly not the value of x. What is happening?

Upvotes: 0

Views: 305

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175065

The Environment provider (which implements the env: drive) only supports string items, and will coerce any assigned value to a [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:

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():

if([bool]::Parse($env:x)){
    'what'
}

... or, if the string value might not be a valid truthy/falsy value, use [bool]::TryParse():

$env:x = $false
$result = $false
if([bool]::TryParse($env:x, [ref]$result) -and $result){
  'what'
}

Upvotes: 3

Related Questions