Search code examples
functionforeachpowershell-5.0

Powershell: how to call a function from inside of a foreach loop?


I'm testing if I can invoke a certain function based on the condition within a foreach loop:

$BROKER = $args[0]    
$MARKETS = $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]


foreach ($market in $MARKETS) {
    if ($market -like 'all') {
        &AllMarkets
        break
    }
    else {
        &CertainMarkets
    }
}


function AllMarkets {
    "Checking all markets"
}


function CertainMarkets {
    "Checking certain markets"
}

When I run the script like this:

.\script.ps1 broker all

I get this error:

& : The term 'AllMarkets' is not recognized as the name of a cmdlet, function, script file, or operable program

How to call these functions from inside the foreach loop?


Solution

  • function AllMarkets {
        "Checking all markets"
    }
    
    
    function CertainMarkets {
        "Checking certain markets"
    }
    $BROKER = $args[0]    
    $MARKETS = $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]
    
    
    foreach ($market in $MARKETS) {
        if ($market -like 'all') {
            &AllMarkets
            break
        }
        else {
            &CertainMarkets
        }
    }
    

    The functions should be defined before the loop. Otherwise, the functions are not yet visible.