I got a few questions to my inbox, that is “How to pass the function as a parameter (calling function from another function) using PowerShell”. To answer this, I thought to write a quick article with a simple example. Let us quickly discuss with a simple example.
Example 1:
In the below example, we have two functions named as Supply-Numbers and Show-Numbers. Here the requirement is to invoke/call the Show-Numbers to print the numbers as output.
function Show-Numbers($number)
{
echo “Number is $number”
}function Supply-Numbers($function)
{
$numbers = 1..15
foreach ($number in $numbers)
{
# Here we should call $function and pass in $number
}
}
Example 2: Calling a Function From Another Function in PowerShell
To call another function, you need to use the Invoke-Command cmdlet and pass in the argument using the ArgumentList parameter like below.
Invoke-Command $function -ArgumentList $number
The argument list (-ArgumentList) expects an array as its value. So if you want to pass in more than 1 parameter like a number and a text that would look something like below
Invoke-Command $function -ArgumentList $number, $txtMsg
function Show-Numbers($number)
{
Write-host “From Supply-Numbers: $number”
}
function Supply-Numbers($function)
{
$numbers = 1..15
foreach ($number in $numbers)
{
Invoke-Command $function -ArgumentList $number
}
}Supply-Numbers ${function:\Show-Numbers}
Note:
- “function:” ( prefix ), is used to access the function object’s script block without executing it.
- The Function provider gives you access to all functions available in PowerShell ant the Function provider gives you access to all functions available in PowerShell
OUTPUT:
Example 2: using -scriptBlockToCall cmdlet
function Show-Numbers {
Param($scriptBlockToCall)
Write-Host “Input from Supply-Numbers Function : $(&$scriptBlockToCall)”
}Function Supply-Numbers {
return “1”
}Show-Numbers -scriptBlockToCall { Supply-Numbers }