Return does not work as expected in Class method

Hi,
I am mad of how unpredictably break, continue and return behave in Powershell, namely for example if you have two nested loops. If two nested loops, then break breaks everything strange way.

However, today I have come across another unexplainable behaviour



Class EndFinder {
    [string[]]$Exclusions_End_Text=@(" of", " of the", " of a", "for a", "for the", " in", " the")
    EndFinder(){}

    [boolean]Contains_Exclusion_At_The_End ([string]$ClipText) {
       #$found=$false
       $this.Exclusions_End_Text |foreach { 
            $exclusion_length=$_.Length
            $clip_length=$ClipText.Length
            if ($exclusion_length -lt $clip_length) {
               $tailing=$ClipText.Substring($clip_length-$exclusion_length,$exclusion_length)
               if ($tailing -eq $_) {
                    #$found=$true
                    return $true
               }
            }
       }
       return $false
       #return $found
    }
}

$kb=[EndFinder]::New()
$kb.Contains_Exclusion_At_The_End("big problem of the")

The purpose of this piece of code is to find whether the segment contains one of the possibilities named specifically in the array, at the end (not all the segment).

Note when debugging, when it comes to " of the" the I’d expect Method Contains_Exclusion_At_The_End shall return/end.
It does not.
Instead, it keeps iterating the loop.

I have to obfuscate the behaviour by using $found variable, but this does not avoid stupid iterating the items until the end.

I know they may be more ellegant way how to to it via calcualted property. But anyway. The return behaves oddly.

Do you know what mistake I do ? Or is powershell really so stupid language ?

Hi, welcome to the forum :wave:

So I’m not exactly sure of the technicalities behind the behaviour but what you’re seeing is the difference between foreach and ForEach-Object.

To take a simplified version of your class to illustrate:

Class EndFinder {
    [string[]]$Exclusions_End_Text=@(" of", " of a", "for a", "for the", " in", " the"," of the")

    [boolean]TestForeachObject() {
        Write-Host "Testing ForEach-Object"
        $this.Exclusions_End_Text | ForEach-Object {
            Write-Host $_
            return $true
        }
        return $false
    }
    [boolean]TestForeach() {
        Write-Host "Testing foreach"
        foreach ($end in $this.Exclusions_End_Text) {
            Write-Host $end
            return $true
        }
        return $false
    }
}


$kb=[EndFinder]::New()
$kb.TestForeachObject()
$kb.TestForeach()