Safely converting string to bool in PowerShell
You could use a try / catch block:
$a = "bla"
try {
$result = [System.Convert]::ToBoolean($a)
} catch [FormatException] {
$result = $false
}
Gives:
> $result
False
Another possibility is to use the switch statemement and only evaluate True
, 1
and default
:
$a = "Bla"
$ret = switch ($a) { {$_ -eq 1 -or $_ -eq "True"}{$True} default{$false}}
In this if the string equals to True
$true
is returned. In all other cases $false
is returned.
And another way to do it is this:
@{$true="True";$false="False"}[$a -eq "True" -or $a -eq 1]
Source Ternary operator in PowerShell by Jon Friesen
$a = 'bla'
$a = ($a -eq [bool]::TrueString).tostring()
$a
False
TryParse
should work as long as you use ref
and declare the variable first:
$out = $null
if ([bool]::TryParse($a, [ref]$out)) {
# parsed to a boolean
Write-Host "Value: $out"
} else {
Write-Host "Input is not boolean: $a"
}