[bool]0 #false [bool]-1 #true [bool]'' #false [bool]' ' #true [bool]"" #false [bool]" " #true [bool]"0" #true [bool]"-1" #true [bool]"1" #true [bool]"$true" #true [bool]"$false" #true [bool]$false #false [bool]$null #falseAlbo taki o to przykład:
$persistent = “False” [boolean]$persistent #trueJak się zastosuje inne metody to wszystko jest dobrze:
[boolean][System.Convert]::ToBoolean( $persistent) #false [bool]::Parse($persistent) #falseOprócz logiki dwuwartościowej może istnieć logika trójwartościowa (niewiadoma). Do takiej konwersji już ciężko jest zastosować typ bool.
Dlatego też stworzyłem funkcję do konwersji string na bool:
$TrueValues = @("yes", "y", "1", "tak")
$FalseValues = @("no", "n", "0", "nie")
function ConvertTo-Bool
{
param(
[Parameter(Mandatory=$true)]
$value,
[switch]$nullable
)
[bool]$outBool = $false
if (![bool]::TryParse($value, [ref] $outBool)) #[ref] for ref and out parameter
{
[bool] $containsInTrue = $TrueValues -contains $value;
if ($nullable)
{
if ($containsInTrue)
{
return $true;
}
if ($FalseValues -contains $value)
{
return $false;
}
return $null;
}
return $containsInTrue;
}
return $outBool
}
A poniżej przykłady użycia funkcji do konwersji:ConvertTo-Bool "false" #$false ConvertTo-Bool "falsssse" #$false ConvertTo-Bool "true" #$true ConvertTo-Bool "false" -nullable #$false $shoud_be_null = ConvertTo-Bool "falsssse" -nullable #$null ConvertTo-Bool "true"-nullable #$true ConvertTo-Bool "nie" #$false ConvertTo-Bool "tak" #$true ConvertTo-Bool "nie" -nullable #$false ConvertTo-Bool "tak" -nullable #$true
Brak komentarzy:
Prześlij komentarz