将字符串值“$false”转换为布尔变量
Convert string value "$false" to boolean variable
我这样做的原因
我正在尝试在我拥有的文件中设置令牌。 token的内容是文件中的1行,它的字符串值为$token=$false
简化为测试代码
当我尝试将此标记转换为布尔值时,我遇到了一些问题。所以我写了测试代码,发现我无法将字符串转换为布尔值。
[String]$strValue = "$false"
[Bool]$boolValue = $strValue
Write-Host '$boolValue =' $boolValue
这会产生以下错误...
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
如您所见,我正在使用错误消息建议的 $false
值,但它不接受它。有什么想法吗?
在 PowerShell 中,常用的转义字符是反引号。插入普通字符串:PowerShell 可以理解和解析 $
符号。您需要转义 $
以防止插值。这应该适合你:
[String]$strValue = "`$false"
要以通用方式将“$true”或“$false”转换为布尔值,您必须先删除前导 $
:
$strValue = $strValue.Substring(1)
然后转换为布尔值:
[Boolean]$boolValue = [System.Convert]::ToBoolean($strValue)
使用您评论中的代码,最短的解决方案是:
$AD_Export_TokenFromConfigFile =
[System.Convert]::ToBoolean(Get-Content $AD_Export_ConfigFile
| % {
If($_ -match "SearchUsersInfoInAD_ConfigToken=") {
($_ -replace '*SearchUsersInfoInAD_ConfigToken*=','').Trim()
}
}.Substring(1))
我这样做的原因
我正在尝试在我拥有的文件中设置令牌。 token的内容是文件中的1行,它的字符串值为$token=$false
简化为测试代码
当我尝试将此标记转换为布尔值时,我遇到了一些问题。所以我写了测试代码,发现我无法将字符串转换为布尔值。
[String]$strValue = "$false"
[Bool]$boolValue = $strValue
Write-Host '$boolValue =' $boolValue
这会产生以下错误...
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
如您所见,我正在使用错误消息建议的 $false
值,但它不接受它。有什么想法吗?
在 PowerShell 中,常用的转义字符是反引号。插入普通字符串:PowerShell 可以理解和解析 $
符号。您需要转义 $
以防止插值。这应该适合你:
[String]$strValue = "`$false"
要以通用方式将“$true”或“$false”转换为布尔值,您必须先删除前导 $
:
$strValue = $strValue.Substring(1)
然后转换为布尔值:
[Boolean]$boolValue = [System.Convert]::ToBoolean($strValue)
使用您评论中的代码,最短的解决方案是:
$AD_Export_TokenFromConfigFile =
[System.Convert]::ToBoolean(Get-Content $AD_Export_ConfigFile
| % {
If($_ -match "SearchUsersInfoInAD_ConfigToken=") {
($_ -replace '*SearchUsersInfoInAD_ConfigToken*=','').Trim()
}
}.Substring(1))