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; }
}
}
@ChrisMagnuson
Copy link

Just what I was looking for, thanks!

You cannot send pull requests for Gists but to make this more consistent with other ConvertTo- functions I have updated this here (https://gist.github.com/ChrisMagnuson/92ebde76384af02dcc62#file-convertto-boolean-ps1) to support input from the pipeline so you can do something like

$Variable | ConvertTo-Boolean

@m1m1k
Copy link

m1m1k commented Nov 30, 2017

I'm adding in "1" and "0" to the switch statement which I think you should too.

@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