I'm trying to set a token in a file I have. The contents of the token is 1 line in the file, and it's string value is $token=$false
When I try to convert this token into a bool value, I'm having some problems. So I wrote test code and found I'm not able to convert the string to a bool value.
[String]$strValue = "$false"
[Bool]$boolValue = $strValue
Write-Host '$boolValue =' $boolValue
This gives the following error...
Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.
At :line:2 char:17
+ [Bool]$boolValue <<<< = $strValue
As you can see, I am using the $false
value as is suggested by the error message, but it's not accepting it. Any ideas?
To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false.
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');
Use the Boolean function to convert other types to a Boolean value. A Boolean value is true, false, or blank. In most cases, type coercion happens automatically and the Boolean function need not be used explicitly.
In PowerShell, the usual escape character is the backtick. Normal strings are interpolated: the $
symbol is understood and parsed by PowerShell. You need to escape the $
to prevent interpolation. This should work for you:
[String]$strValue = "`$false"
To convert "$true" or "$false" to a boolean in a generic way, you must first drop the leading $
:
$strValue = $strValue.Substring(1)
Then convert to boolean:
[Boolean]$boolValue = [System.Convert]::ToBoolean($strValue)
Using your code from your comment, the shortest solution would be:
$AD_Export_TokenFromConfigFile =
[System.Convert]::ToBoolean(Get-Content $AD_Export_ConfigFile
| % {
If($_ -match "SearchUsersInfoInAD_ConfigToken=") {
($_ -replace '*SearchUsersInfoInAD_ConfigToken*=','').Trim()
}
}.Substring(1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With