Return Boolean from Function in PowerShell

Return Boolean from Function in PowerShell

Using Predefined Variables – $True and $False

To return Boolean from function in PowerShell, use predefined variables: $True, $False.

In PowerShell, a Boolean value can be either True or False. However, the Boolean data type represents the true/false conditions for use in conditional statements, comparisons, and logical operations.

The following values are True in PowerShell:

  • The True variable.
  • The number 1.
  • The string "True" (case-insensitive).
  • Any non-empty string.
  • Any non-zero number.
  • Any object that is not False or Null.

The False values in PowerShell are as follows:

  • The False variable.
  • The number 0.
  • The string "False" (case-insensitive).
  • The empty string "".
  • The Null variable.

We can use these predefined variables in conditional statements, such as if and while loops, to check if a condition is true or false. For example, we used the variables in the if-else block that checks if num1 and num2 are equal. If so, it returns the predefined variable True, else False.

At last, we provided the compareNumbers function with two equal numbers as parameters and called it. The function returned True. If we call the compareNumbers function with two unequal numbers:

As the numbers 2 and 3 are unequal, the script displayed the False message on the console.

Using return statement with condition

To return Boolean from function in PowerShell:

  • Use the function to create a function with two integer parameters.
  • Use the -eq operator to compare the two provided numbers and return the Boolean output value.
  • Use the function by calling its name along with two arguments.

A function in PowerShell is a block of code that can take parameters, perform a set of tasks, and return values. It makes the code reusable and allows us to create powerful scripts. A function has the same syntax as other scripts but with parameters and the function keyword at the beginning. However, scripts and commands use it simply by calling it by its name. For example, we created a function compareNumbers that holds two integer type parameters: num1 and num2.

The comparison operator -eq in PowerShell compares two values for equality. It compares the values on either side of the operator and returns True if they are equal or False if not. For example, the compareNumbers function compares two numbers using the -eq operator and returns a Boolean value.

Finally, we called the function by providing two equal numbers as parameters. The function returned True that the script printed on the console. If we call the compareNumbers function with two unequal numbers:

The script displayed the False message on the console as the numbers 2 and 3 were unequal.

That’s all about how to return boolean from function in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *