Convert string value "$ false" to a boolean variable

The reason I do it

I am trying to set a token in a file that I have. The content of the token is 1 line in the file, and this is the string value $token=$false

Simplified verification code

When I try to convert this token to a bool value, I have some problems. Therefore, I wrote test code and found that I could not 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 use the value $false , as this suggests an error message, but it does not accept it. Any ideas?

+5
source share
1 answer

In PowerShell, the usual escape character is the flip side. Standard lines are interpolated: the $ character is understood and parsed by PowerShell. To prevent interpolation, you need to avoid $ . This should work for you:

 [String]$strValue = "`$false" 

To convert $ true or $ false to boolean in general, you must first transfer 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)) 
+7
source

Source: https://habr.com/ru/post/1245950/


All Articles