mark
mark

Reputation: 62712

How to pass a function to script in powershell?

C:\tmp\run.ps1:

function buildOne()
{
    param(
        [Parameter(Mandatory=$true)][string]$a,
        [Parameter(Mandatory=$true)][string]$b
    )
    Write-Host -ForegroundColor yellow "$a $b"
}

C:\tmp\_build.ps1 {$Function:buildOne}

C:\tmp_build.ps1:

param(
    [Parameter(Mandatory=$true)]$buildOne
)

#&$buildOne "a" "b"
#Invoke-Command $buildOne -argumentlist "a", "b"
#Invoke-Command -ScriptBlock $buildOne -argumentlist "a", "b"

The idea is to invoke the buildOne function passed as parameter from run.ps1 to _build.ps1. Unfortunately, none of my attempts works. For some reason it just displays the function body rather than invokes it.

What am I doing wrong?

Upvotes: 1

Views: 67

Answers (1)

Keith Hill
Keith Hill

Reputation: 201602

You can invoke commands (and functions) by name as long as they are in scope:

C:\tmp_build.ps1 buildOne

tmp_build.ps1

& $buildOne a b 

If you really want to pass the function definition then do it like this:

run.ps1

function buildOne()
{
    param(
        [Parameter(Mandatory=$true)][string]$a,
        [Parameter(Mandatory=$true)][string]$b
    )
    Write-Host -ForegroundColor yellow "$a $b"
}

.\tmp_build.ps1 $Function:buildOne

tmp_build.ps1

param(
    [Parameter(Mandatory=$true)]$buildOne
)

$buildOne.Invoke("a", "b")

Upvotes: 2

Related Questions