[英]Convert string value “$false” to boolean variable
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
令牌的内容在文件中是1行,它的字符串值是
$token=$false
When I try to convert this token into a bool value, I'm having some problems. 当我尝试将此令牌转换为bool值时,我遇到了一些问题。 So I wrote test code and found I'm not able to convert the string to a bool value.
所以我写了测试代码,发现我无法将字符串转换为bool值。
[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. 正如您所看到的,我正在使用错误消息建议的
$false
值,但它不接受它。 Any ideas? 有任何想法吗?
In PowerShell, the usual escape character is the backtick. 在PowerShell中,通常的转义字符是反引号。 Normal strings are interpolated: the
$
symbol is understood and parsed by PowerShell. 插入普通字符串: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 $
: 要以通用方式将“$ true”或“$ false”转换为布尔值,必须首先删除前导
$
:
$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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.