Boolean literals in PowerShell

前端 未结 3 991
陌清茗
陌清茗 2020-12-14 13:28

What are the boolean literals in PowerShell?

相关标签:
3条回答
  • 2020-12-14 14:16

    [bool]1 and [bool]0 also works.

    0 讨论(0)
  • 2020-12-14 14:22

    To add more information to already existing answers: The boolean literals $true and $false also work as is when used as command line parameters for PowerShell (PS) scripts. For the below PS script which is stored in a file named installmyapp.ps1:

    param (
        [bool]$cleanuprequired
    )
    
    echo "Batch file starting execution."
    

    Now if I've to invoke this PS file from a PS command line, this is how I can do it:

    installmyapp.ps1 -cleanuprequired $true
    

    OR

    installmyapp.ps1 -cleanuprequired 1
    

    Here 1 and $true are equivalent. Also, 0 and $false are equivalent.

    Note: Never expect that string literal true can get automatically converted to boolean. For example, if I run the below command:

    installmyapp.ps1 -cleanuprequired true
    

    it fails to execute the script with the below error:

    Cannot process argument transformation on parameter 'cleanuprequired'. Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.

    0 讨论(0)
  • 2020-12-14 14:31

    $true and $false.

    Those are constants, though. There are no language-level literals for booleans.

    Depending on where you need them, you can also use anything that coerces to a boolean value, if the type has to be boolean, e.g. in method calls that require boolean (and have no conflicting overload), or conditional statements. Most non-null objects are true, for example. null, empty strings, empty arrays and the number 0 are false.

    0 讨论(0)
提交回复
热议问题