Skip to content

Instantly share code, notes, and snippets.

@kyle-herzog
Created October 28, 2012 00:47
Show Gist options
  • Save kyle-herzog/3967052 to your computer and use it in GitHub Desktop.
Save kyle-herzog/3967052 to your computer and use it in GitHub Desktop.
Convert common values to Powershell boolean values $true and $false
function ConvertTo-Boolean
{
param
(
[Parameter(Mandatory=$false)][string] $value
)
switch ($value)
{
"y" { return $true; }
"yes" { return $true; }
"true" { return $true; }
"t" { return $true; }
1 { return $true; }
"n" { return $false; }
"no" { return $false; }
"false" { return $false; }
"f" { return $false; }
0 { return $false; }
}
}
@ayseff
Copy link

ayseff commented Apr 29, 2018

What if it's none of those values? Then it just returns $null? How about deciding on whitelisting or blacklisting, and also condensing the code a drop, such as:

function ConvertTo-Boolean
{
  param
  (
    [Parameter(Mandatory=$false,ValueFromPipeline=$true)][string] $value
  ) 
  return @("y", "t", "true", "1").Contains($value)
}

You can also just use the [bool]::Parse or [bool]::TryParse functions, but then you won't have all the fancy scenarios which you enumerated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment