I'm trying to convert an argument of my PowerShell script to a boolean value. This line
[System.Convert]::ToBoolean($a)
works fine as long as I use valid values such as "true" or "false", but when an invalid value, such as "bla" or "" is passed, an error is returned. I need something akin to TryParse, that would just set the value to false if the input value is invalid and return a boolean indicating conversion success or failure. For the record, I tried [boolean]::TryParse and [bool]::TryParse, PowerShell doesn't seem to recognize it.
Right now I'm having to clumsily handle this by having two extra if statements.
What surprised me that none of the how-to's and blog posts I've found so far deal with invalid values. Am I missing something or are the PowerShell kids simply too cool for input validation?
You could use a try / catch block:
Gives:
TryParse
should work as long as you useref
and declare the variable first:just looked for this again and found my own answer - but as a comment so adding as an answer with a few corrections / other input values and also a pester test to verify it works as expected:
Another possibility is to use the switch statemement and only evaluate
True
,1
anddefault
: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:
Source Ternary operator in PowerShell by Jon Friesen