Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

powershell - Pass function as a parameter

I've written function 'A' that will call one of a number of other functions. To save re-writing function 'A', I'd like to pass the function to be called as a parameter of function 'A'. For example:

function A{
    Param($functionToCall)
    Write-Host "I'm calling : $functionToCall"
}

function B{
    Write-Host "Function B"
}

Function C{
    write-host "Function C"
}

A -functionToCall C

Returns: I'm calling: C

I am expecting it to return: I'm calling: Function C.

I've tried various things such as:

Param([scriptblock]$functionToCall)

Cannot convert System.String to ScriptBlock

A -functionToCall $function:C

Returns "Write-Host "Function C"

A - functionToCall (&C)

This evaluates before the rest of it:

 Function C
 I'm Calling :

I'm sure this is programming 101, but I can't work out the correct syntax or what it is I'm doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure this is the best, but:

function A{
    Param([scriptblock]$FunctionToCall)
    Write-Host "I'm calling $($FunctionToCall.Invoke(4))"
}

function B($x){
    Write-Output "Function B with $x"
}

Function C{
    Param($x)
    Write-Output "Function C with $x"
}

PS C:WINDOWSsystem32> A -FunctionToCall $function:B
I'm calling Function B with 4

PS C:WINDOWSsystem32> A -FunctionToCall $function:C
I'm calling Function C with 4

PS C:WINDOWSsystem32> A -FunctionToCall { Param($x) "Got $x" }
I'm calling Got x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...