PowerShell script to return true or false, takes two input params

Viewed 43

I have a requirement, I have to write a powershell script with two input params, and this script should return true or false.

Parameter1: Path of a text file which contains a list of file names ( ex: a.txt, test.dll etc).

Parameter2: Search directory. (has folders and subfolders)

I have to search for the fileNames listed in the textfile (input parameter1) in the searchDirectory(parameter2). If any of the fileName exists in any of the (searchDirectory or its folders or subfolders) the script should return 1 else 0.

Please find my below code which is incomplete. Im not sure how to capture GetChildItem result to return 0 or 1. Please help me with script to achieve the requirement. Thanks in advance.

param(
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]
    $textFilePath,
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]
    $searchDirectory
)

foreach($FileName in [System.IO.File]::ReadLines($textFilePath))
{
    Get-ChildItem -Path $searchDirectory -Filter $Filename -Recurse
}
1 Answers

If I understand correctly your requirement, you're looking to exit early from your script at first appearance of one of the files, for that you can use the return keyword. The script's body would look like this:

foreach($FileName in [System.IO.File]::ReadLines($textFilePath)) {
    # if the file could be found
    if(Get-ChildItem -Path $searchDirectory -Filter $Filename -Recurse) {
        return 1 # exit early from the script here
    }
}
return 0 # return is not needed here

There is also another alternative that might be more efficient, instead of using -Filter you could use -Include which can take an array:

# get an array of all lines in the file, exclude empty lines
$files = @([System.IO.File]::ReadAllLines($textFilePath)) -ne ''
# `Select-Object -First 1` can be used to stop the pipeline at first appeareance of a file
if(Get-ChildItem -Path $searchDirectory -Include $files -Recurse | Select-Object -First 1) {
    return 1 # exit early from the script here
}
return 0 # return is not needed here
Related