Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely converting string to bool in PowerShell

Tags:

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?

like image 924
Shaggydog Avatar asked Dec 15 '14 13:12

Shaggydog


People also ask

How do you change a string from true to boolean true?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');

What is :$ false in PowerShell?

PowerShell Boolean operators are $true and $false which mentions if any condition, action or expression output is true or false and that time $true and $false output returns as respectively, and sometimes Boolean operators are also treated as the 1 means True and 0 means false.


2 Answers

You could use a try / catch block:

$a = "bla" try {   $result = [System.Convert]::ToBoolean($a)  } catch [FormatException] {   $result = $false } 

Gives:

> $result False 
like image 187
arco444 Avatar answered Nov 09 '22 14:11

arco444


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" } 
like image 33
Mike Zboray Avatar answered Nov 09 '22 13:11

Mike Zboray