PowerShell: How to Create Function that Returns True / False


When creating a PowerShell function, we can use an if statement within the function to return either $true or $false values, which evaluate to True and False.

For example, we can create the following function to check if a particular folder contains any CSV files and return either True or False as a result:

function containsCSV {
 param($my_path)
 $successContains = Get-ChildItem -path $my_path -recurse -include "*.csv"
    if ($successContains) {
        return $true;
    }
    return $false;
}

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

Example: How to Create Function that Returns True or False in PowerShell

Suppose that we would like to create a function that checks if a particular folder contains any CSV files and returns either True or False as a result.

We can use the following syntax to create this function:

function containsCSV {
 param($my_path)
 $successContains = Get-ChildItem -path $my_path -recurse -include "*.csv"
    if ($successContains) {
        return $true;
    }
    return $false;
}

The variable in the function named $successContains will return all of the files that have .csv extensions in the path specified by $my_path.

Then we use an if statement to check if the number of files returned is greater than zero and simply return $true or $false as a result.

Suppose that we would like to use this function to check if a folder with the following path has any CSV files:

  • c:\users\bobbi\data1

We can use the Get-ChildItem cmdlet to first view the files in this folder:

We can then use the containsCSV() function we just created to check if this folder contains any CSV files:

PowerShell create function to return true or false

The function returns a value of True since the path that we specified does indeed contain at least one CSV file.

Suppose we have another folder with the following path:

  • c:\users\bobbi\data2

We can use the Get-ChildItem cmdlet to first view the files in this folder:

We can then use the containsCSV() function we just created to check if this folder contains any CSV files:

The function returns a value of False since the path that we specified does not contain at least one CSV file.

Feel free to use similar syntax to create your own function that returns either $true or $false as a result.

Related Tutorials

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

PowerShell: How to Return Multiple Values from Function
PowerShell: How to Create a Custom Input Box
PowerShell: How to Find N Largest Files in a Directory

Leave a Reply