Safely converting string to bool in PowerShell

前端 未结 6 1369
孤城傲影
孤城傲影 2020-12-18 19:03

I\'m trying to convert an argument of my PowerShell script to a boolean value. This line

[System.Convert]::ToBoolean($a)

works fine as long

6条回答
  •  一整个雨季
    2020-12-18 19:45

    TryParse should work as long as you use ref and declare the variable first:

    $out = $null
    if ([bool]::TryParse($a, [ref]$out)) {
        # parsed to a boolean
        Write-Host "Value: $out"
    } else {
        Write-Host "Input is not boolean: $a"
    }
    

提交回复
热议问题