简体   繁体   English

如何在Powershell中将函数传递给脚本?

[英]How to pass a function to script in powershell?

C:\\tmp\\run.ps1: 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: 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 . 想法是调用从参数run.ps1传递到_build.ps1buildOne函数。 Unfortunately, none of my attempts works. 不幸的是,我的尝试均无济于事。 For some reason it just displays the function body rather than invokes it. 由于某种原因,它仅显示函数体而不是调用它。

What am I doing wrong? 我究竟做错了什么?

You can invoke commands (and functions) by name as long as they are in scope: 您可以按名称调用命令(和函数),只要它们在范围内即可:

C:\tmp_build.ps1 buildOne

tmp_build.ps1 tmp_build.ps1

& $buildOne a b 

If you really want to pass the function definition then do it like this: 如果您真的想传递函数定义,请按以下步骤进行:

run.ps1 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 tmp_build.ps1

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM