convert "Yes" or "No" to boolean convert "Yes" or "No" to boolean powershell powershell

convert "Yes" or "No" to boolean


One way is a switch statement:

$bool = switch ($string) {  'yes' { $true }  'no'  { $false }}

Add a clause default if you want to handle values that are neither "yes" nor "no":

$bool = switch ($string) {  'yes'   { $true }  'no'    { $false }  default { 'neither yes nor no' }}

Another option might be a simple comparison:

$string -eq 'yes'            # matches just "yes"

or

$string -match '^y(es)?$'    # matches "y" or "yes"

These expressions would evaluate to $true if the string is matched, otherwise to $false.


Ah, the magic of powershell functions, and invoke expression.

function Yes { $true }function No { $false }$magicBool = & $answer 

Note: This is case insensitive, but will not handle misspellings


If the only possible values are "Yes" and "No" then probably the simplest way is

$result = $value -eq 'Yes'

With misspelled values and the default $false the above will do as well.

With misspelled values and the default $true this will work

$result = $value -ne 'No'