Search code examples
powershellwindows-scripting

Powershell function not executing as expected


I have the following function that shows if any of the words in an array are contained in a string:

function AnyOf ([string] $line, [string[]] $list)
{
    Write-Output "AnyOf!"
    foreach($item in $list)
    {   
        if($line.Contains($item))
        {
            Write-Output "Found: $item" 
            return $true
        }
    }
    return $false
}

And this to test it:

function main
{   
    [string[]]$a = @("user1", "user2")
    $str = "user1 and user2"
    $res = AnyOf($str, $a)
}

I expect it to see both user1 and user2 to get printed out but nothing is printed. It appears as though the function isn't getting called because the Write-Output "AnyOf!" is never executed.

However, when I execute:

AnyOf($str, $a)

Instead of:

$res = AnyOf($str, $a)

I can see that the function is called but the iteration doesn't seem to happen... What am I doing wrong?


Solution

  • A few things,

    First of all, functions in powershell are not called using () you would call the function as

    AnyOf $str $a

    The standard convention is $<<nameOfFunction>> <<param1>> <<param2>>

    Secondly, your output is being captured in $res and therefore not printed to the screen, if you add $res at the end of your main function it will output.

    So your main function becomes:

    function main
    {   
        [string[]]$a = @("user1", "user2")
        $str = "user1 and user2"
        $res = AnyOf $str $a
        $res #or just don't assign it to $res..
    }
    
    
    #to call main:
    main
    
    Output:
    
    AnyOf!
    Found: user1
    True
    

    As you can see in the above output it never finds User2 because you use a return $true once it finds a match, exiting out of the function.

    Another thing to note is that when you return $false or $true these actually become part of the output stream, which might not be what you want as it can lead to unexpected behavior.