如何在运行空间脚本块中调用外部定义的函数

How to call outside defined function in runspace scriptblock

我有一个复杂的 PowerShell 函数,我想 运行 另一个线程。

但是,如果我是对的,则无法在脚本块中访问该函数。我想避免复制它旁边的每个相关功能。

有什么方法可以调用脚本块中的函数吗?

function Function1 {
    Param()
    Process {
        $param1 = "something"
        $pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1)
        $pool.ApartmentState = "MTA"
        $pool.Open()
        $runspaces = @()

        $scriptblock = {
            Param (
                [Object] [Parameter(Mandatory = $true)] $param1
            )
            Complex_Function -param1 $param1
        }

        1..10 | ForEach-Object {
            $runspace = [PowerShell]::Create()
            $null = $runspace.AddScript($scriptblock)
            $null = $runspace.AddArgument($param1)
            $runspace.RunspacePool = $pool
            $runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
        }

        while ($runspaces.Status -ne $null) {
            $completed = $runspaces | Where-Object { $_.Status.IsCompleted -eq $true }
            foreach ($runspace in $completed) {
                $runspace.Pipe.EndInvoke($runspace.Status)
                $runspace.Status = $null
            }
        }

        $pool.Close()
        $pool.Dispose()
    }
}

function Complex_Function {
    Param(
        [Object] [Parameter(Mandatory = $true)] $param1
    )
    Process {
        #several function calls 
    }
}

我认为 this blog post 中的代码可能就是您要查找的代码:

Function ConvertTo-Hex {
    Param([int]$Number)
    '0x{0:x}' -f $Number
}

#Get body of function
$Definition = Get-Content Function:\ConvertTo-Hex -ErrorAction Stop

#Create a sessionstate function entry
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry 
    -ArgumentList 'ConvertTo-Hex', $Definition

#Create a SessionStateFunction

$InitialSessionState.Commands.Add($SessionStateFunction)

 #Create the runspacepool by adding the sessionstate with the custom function

$RunspacePool = [runspacefactory]::CreateRunspacePool(1,5,$InitialSessionState,$Host)

对你的 Complex_Function 和(我猜)你需要的所有其他功能做一些类似的事情,你的运行空间应该可以使用它们。

编辑 您在评论中询问如何收集所有功能。路径function:/可以像目录一样遍历和查找,所以get-chiditem function:/得到所有当前定义的函数

在对此进行试验时,似乎在当前脚本中定义的函数或来自点源脚本的函数有一个空 Source 属性。玩这个。它应该导致你想要的。

$InitialSessionState = [initialsessionstate]::Create()

Get-ChildItem function:/ | Where-Object Source -like "" | ForEach-Object {
    $functionDefinition = Get-Content "Function:$($_.Name)"
    $sessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry `
        -ArgumentList $_.Name, $functionDefinition 
    $InitialSessionState.Commands.Add($sessionStateFunction)
}