Fid*_*eak 6 powershell powershell-3.0
我正在尝试在我拥有的文件中设置令牌.令牌的内容在文件中是1行,它的字符串值是$token=$false
当我尝试将此令牌转换为bool值时,我遇到了一些问题.所以我写了测试代码,发现我无法将字符串转换为bool值.
[String]$strValue = "$false"
[Bool]$boolValue = $strValue
Write-Host '$boolValue =' $boolValue
Run Code Online (Sandbox Code Playgroud)
这给出了以下错误......
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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在使用$false错误消息建议的值,但它不接受它.有任何想法吗?
在PowerShell中,通常的转义字符是反引号.内插正常字符串:$PowerShell理解和解析符号.你需要逃避$以防止插值.这应该适合你:
[String]$strValue = "`$false"
Run Code Online (Sandbox Code Playgroud)
要以通用方式将"$ true"或"$ false"转换为布尔值,必须首先删除前导$:
$strValue = $strValue.Substring(1)
Run Code Online (Sandbox Code Playgroud)
然后转换为布尔值:
[Boolean]$boolValue = [System.Convert]::ToBoolean($strValue)
Run Code Online (Sandbox Code Playgroud)
使用评论中的代码,最短的解决方案是:
$AD_Export_TokenFromConfigFile =
[System.Convert]::ToBoolean(Get-Content $AD_Export_ConfigFile
| % {
If($_ -match "SearchUsersInfoInAD_ConfigToken=") {
($_ -replace '*SearchUsersInfoInAD_ConfigToken*=','').Trim()
}
}.Substring(1))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6626 次 |
| 最近记录: |