Safely converting string to bool in PowerShell

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

    Another possibility is to use the switch statemement and only evaluate True, 1 and default:

    $a = "Bla"
    $ret = switch ($a) { {$_ -eq 1 -or $_ -eq  "True"}{$True} default{$false}}
    

    In this if the string equals to True $true is returned. In all other cases $false is returned.

    And another way to do it is this:

    @{$true="True";$false="False"}[$a -eq "True" -or $a -eq 1]
    

    Source Ternary operator in PowerShell by Jon Friesen

提交回复
热议问题