Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string value "$false" to boolean variable

Reason I'm Doing This

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

Simplified to test code

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?

like image 524
Fiddle Freak Avatar asked Mar 29 '16 00:03

Fiddle Freak


People also ask

Can you convert string to boolean?

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.

How do you turn a variable into a boolean?

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.

How do you change a string from true to boolean true?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');

What function converts a value to a boolean?

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.


1 Answers

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))
like image 84
Paul Hicks Avatar answered Sep 29 '22 07:09

Paul Hicks