Safely converting string to bool in PowerShell

前端 未结 6 1380
孤城傲影
孤城傲影 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:42

    Prior answers are more complete, but if you know that $foo -eq 1, "1", 0, "0", $true, $false... anything that can be coerced to an [int]

    Either of the following statements work:

    [System.Convert]::ToBoolean([int]$foo)
    [System.Convert]::ToBoolean(0 + $foo)
    

    Hope that helps someone that just needs a simple solution.

提交回复
热议问题