Created
October 28, 2012 00:47
-
-
Save kyle-herzog/3967052 to your computer and use it in GitHub Desktop.
Convert common values to Powershell boolean values $true and $false
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
I'm adding in "1" and "0" to the switch statement which I think you should too.
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
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