PowerShell Boolean literals

What are boolean literals in PowerShell?

+99
powershell
May 14 '12 at 10:05
source share
3 answers

$true and $false .

These are constants. There are no level literals for Boolean languages.

Depending on where you need them, you can also use anything that resorts to a boolean if the type should be boolean, for example. in calls to methods that require Boolean (and do not have conflicting overload) or conditional statements. For example, most nonzero objects are true. null , empty strings, empty arrays, and the number 0 are false.

+122
May 14 '12 at 10:06
source share

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

+15
May 15 '12 at 11:16
source share

Just to add more information : the $true and $false boolean literals also work as they are when used as command-line options for PowerShell (PS) scripts. For the PS script below, which is stored in a file called installmyapp.ps1 :

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

Now, if I need to call this PS file from the PS command line, here is how I can do it:

 installmyapp.ps1 -cleanuprequired $true 

OR

 installmyapp.ps1 -cleanuprequired 1 

Here 1 and $true equivalent. In addition, 0 and $false equivalent.

Note Never expect the string literal true to be automatically converted to a boolean value. For example, if I run the following command:

 installmyapp.ps1 -cleanuprequired true 

it cannot execute the script with the error below:

Failed to process argument conversion for 'cleanuprequired' parameter. Cannot convert the value of "System.String" to the type "System.Boolean". Logical parameters accept only logical values ​​and numbers, such as $ True, $ False, 1 or 0.

+3
May 15 '18 at 8:42
source share



All Articles