-1

I want to create a PowerShell script that returns a bunch of file in a given list of directories. This is the function:

function CheckFilesToDelete([string[]]$fList) {
    [System.Collections.Generic.List[System.IO.DirectoryInfo]]$fileList

    foreach($folderName in $fList)
    {
        $path = "$folderName"

        ($list = @(Get-ChildItem "$path" -File -Recurse | 
                 Where-Object { $_.Name -match '.*TMP.*' })) > null
        if($list -ne $null -and $list.Count -gt 0) { 
            $fileList.AddRange($list)
        }
    }

    return $fileList
}

The problem I have is where I try to check if the $list has a value and add the $list to the $fileList. The error is

RuntimeException: You cannot call a method on a null-valued expression

I don't know how to fix it.

Enrico
  • 3,592
  • 6
  • 45
  • 102
  • Please [edit] your question to improve your [mcve]. In particular, share **1st** how do you call the function, and **2nd** _full_ error message… – JosefZ May 02 '23 at 14:50
  • Does this answer your question? [You cannot call a method on a null-valued expression - general](https://stackoverflow.com/questions/31335195/you-cannot-call-a-method-on-a-null-valued-expression-general) – Daniel Mann May 02 '23 at 17:28

1 Answers1

4

First thing to point out, Directories are NOT files. Second, you are not actually creating anything with

[System.Collections.Generic.List[System.IO.DirectoryInfo]]$fileList

You would either need to use new-object or the v5+ ::New() method. However, none of that is needed. It can be simplified greatly

function CheckFilesToDelete([string[]]$fList) {
    foreach($item in $fList) {
        Get-ChildItem $item -File -Recurse -Filter *TMP*

    }
}

Now you just call it like this

$output = CheckFilesToDelete

Finally, you should try to stick with the powershell naming convention of Verb-Noun - especially if these functions are to be shared with others.

Doug Maurer
  • 8,090
  • 3
  • 12
  • 13