How to Create a Boolean Variable in PowerShell (With Example)


You can use the following basic syntax in PowerShell to create a Boolean variable:

[bool]$my_var = $true

This particular example creates a Boolean variable named $my_var that contains the value True.

Note that the $true and $false values are both pre-defined in PowerShell and evaluate to True and False, respectively.

By prepending the variable name with [bool] we are able to explicitly tell PowerShell that this variable should be a Boolean.

The following example shows how to use this syntax in practice.

Example: How to Create a Boolean Variable in PowerShell

We can use the following syntax to create a Boolean variable named $my_var that contains the value True:

[bool]$my_var = $true

The following screenshot shows how to use this syntax in practice:

When we output the value of the $my_var variable we can see that it returns the value True.

Note that we can also use the GetType() command to display the variable type:

$my_var.GetType().Name

The following screenshot shows how to use this syntax in practice:

This returns Boolean, which confirms that the variable we created named $my_var is indeed a Boolean variable.

It’s worth noting that besides $true and $false you could also assign values of 1 and 0 to a Boolean variable, as long as you prepend the variable name with [bool] to specify that the value of 1 or 0 should be evaluated as a Boolean value of True or False.

For example, we can use the following syntax to create a Boolean variable that contains a value of 1:

[bool]$my_var = 1

The following screenshot shows how to use this syntax in practice:

Notice that when we use the GetType() command we can see that $my_var is indeed a Boolean variable.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Convert String to Double
PowerShell: How to Convert String to Datetime
PowerShell: How to Check if Array is Empty

Leave a Reply