Tuesday, July 28, 2009

How to convert [String] to [Boolean]

If you always try to specify the type (as I do), maybe you already figured out that you cannot convert string to boolean in Powershell:

[Boolean]$Var = $True
$Var = “False”

Cannot convert value "System.String" to type "System.Boolean", parameters of th

is type only accept booleans or numbers, use $true, $false, 1 or 0 instead.

At line:1 char:5

+ $Var <<<<  = "False"

    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMet


    + FullyQualifiedErrorId : RuntimeException

Obviously, you should use $False or 0 instead… Sometimes this can be an issue – especially if you read your configuration from XML file, it is returned as string (so it is “0” instead of 0).

There is however workaround for this that allows you to convert string to boolean:

[Boolean]$Var = $False
$Var = [System.Convert]::ToBoolean("True")

1 comment:

Leslie Lim said...

This is really an interesting topic. Congratulations to the writer. I'm sure a lot of readers having fun reading your post. Hoping to read more post from you in the future. Thank you and God bless!